7/28, FB, I/O Buffer


Read N Characters Given Read4

这题的 API 和题目描述都有点模糊,重新理一下:

  • int read4(char[] buf)
  • 你扔一个 char[] 过去,函数写入最多 4 个 char 在上面,然后返回写入 char 的长度; 到文件末尾的时候返回 char 长度会小于 4.

  • 于是我们的目标是把最终长度为 n 的字符串写入自己函数的 read(char[] buf) 里,然后返回实际长度。

主要的注意点就是,有的时候 read4 是短板,有的时候 readN 自己是短板(不需要4个那么多的字符),在写入的时候要注意处理下。

    public int read(char[] buf, int n) {
        int count = 0;
        boolean hasNext = true;
        char[] tmp = new char[4];
        while(count<=n && hasNext){
            int x =read4(tmp);
            if(x<4)
                hasNext = false;
            for(int i=0;i<x && count<n;i++)
                buf[count++] = tmp[i];
        }
        return count;
    }

Read N Characters Given Read4 II - Call multiple times

多次调用之后,这题的难点就变成了 “如何处理剩余字符”。因为一次 call 拿到的字符很可能超过我们实际需要的,这时候就需要依赖外部 buffer 记录下来,每次新 read() call 的时候,先从缓存里拿。

仔细分析后几种情况, 用i记录已读取字符

  1. 剩余字符大于等于当前读取, 先读到i==n, 读到多少返回多少.
  2. 剩余字符不够 进入while loop
    1. 持续读, 读到存不下为止, 将多余的字符存入remain queue
    2. 读到没的读, 这时read4()返回的是小于4的值;返回
    3. 读到4, 持续读
  3. 没有提前返回, 完美读取
     LinkedList<Character> remain = new LinkedList<Character>();
    public int read(char[] buf, int n) {
        int i =0;
        while(i<n&&!remain.isEmpty()){
            buf[i++] = remain.poll();
        }
        if(i==n) return n;

        while(i<n){
            char[] tmp = new char[4];
            int tmpcnt = read4(tmp);
            //read more than need
            if(i+tmpcnt>n){
                int j=0;
                for(;j<n-i;j++)
                    buf[i+j] = tmp[j];
                for(;j<tmpcnt;j++)
                    remain.offer(tmp[j]);
                return n;
            }

            //read less than 4
            if(tmpcnt<4){
                for(int j=0;j<tmpcnt;j++)
                    buf[i+j] = tmp[j];
                return i+tmpcnt;
            }

            //read is 4
            for(int j=0;j<tmpcnt;j++)
                buf[i+j] = tmp[j];
            i=i+tmpcnt;
        }
        return n;
    }

results matching ""

    No results matching ""