158. Read N Characters Given Read4 II - Call multiple times

这题就是用个Deque或者queue把剩的先存下来下次用。
思路就是这么简单,实现的时候要小心一点判断什么时候退出。
我里面出了一个bug就是for loop里的那个i, 我在for 的语句里已经++了
结果在花括号里又++了一次就出了bug。

public class Solution extends Reader4 {
    /**
     * @param buf Destination buffer
     * @param n   Number of characters to read
     * @return    The number of actual characters read
     */
    Deque deque;
    public Solution() {
        //constructor, intialize deque to hold extra character
        deque = new ArrayDeque<>();
    }
    public int read(char[] buf, int n) {
        int index = 0;
        char[] buf4 = new char[4];
        //read from deque
        while (!deque.isEmpty() && index < n) buf[index++] = deque.pollFirst();
        if (index == n) return index;
        //if needed, read from buf
        while (index < n) {
            //while loop for read4
            int actualRead = read4(buf4);

            //if read 0, file ended, return what ever read so far
            if (actualRead == 0) return index;
            // transfer to the buf
            int i = 0;
            for (i = 0; i < actualRead && index < n; i++) {
                buf[index++] = buf4[i]; //bug用了i++之后这里就不用再加了
            }      
            // put the left over back to the deque
            while (i < actualRead) deque.offerLast(buf4[i++]);
        }
        // return 
        return index;
        
    }
}

你可能感兴趣的:(158. Read N Characters Given Read4 II - Call multiple times)