The API: int read4(char *buf) reads 4 characters at a time from a file.

The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file.

By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.

Note:
The read function may be called multiple times.

 

和157题一样,区别在于可以对一个文件多次使用read

 

那么区别就是在于如果之前调用过一次read,可能由于调用了read4的原因,会出现多读了几个字母(小于4个),那么设定一个变量即可。存储当前多读取的字母长度和字母。

1、需要注意的点:多次调用的时候,moreChars里的字母可能没有用完。

 

/* The read4 API is defined in the parent class Reader4.
      int read4(char[] buf); */

public class Solution extends Reader4 {
    /**
     * @param buf Destination buffer
     * @param n   Maximum number of characters to read
     * @return    The number of characters read
     */
    private int len = 0;
    private char[] moreChars = new char[3];
    public int read(char[] buf, int n) {
        if (n < 1){
            return 0;
        }
        int result = 0;
        if (len != 0){
            int count = Math.min(n, len);
            for (int i = 0; i < count; i++){
                buf[i] = moreChars[i];
                result++;
            }
            for (int i = 0; i < (len - count); i++){
                moreChars[i] = moreChars[count + i];
            }
            len -= count;
        }
        char[] chars = new char[4];
        int times = (n - result) / 4;
        for (int i = 0; i < times; i++){
            int count = read4(chars);
            for (int j = 0; j < count; j++){
                buf[result + j] = chars[j];
            }
            result += count;
            if (count < 4){
                return result;
            }
        }
        if (n == result){
            return result;
        }
        int count = read4(chars);
        for (int i = 0; i < Math.min(n - result, count); i++){
            buf[result + i] = chars[i];
        }
        if (n - result < count){
            len = count - n + result;
            for (int i = 0; i < len; i++){
                moreChars[i] = chars[n - result + i];
            }
        }
        result += Math.min(n - result, count);
        return result;
    }
}