Read N Characters Given Read4 II – Call multiple times

NO IMAGE

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.

思路:

第一次呼叫時,如果read4讀出的多餘字元我們要先將其暫存起來,這樣第二次呼叫時先讀取這些暫存的字元

第二次呼叫時,如果連暫存字元都沒讀完,那麼這些暫存字元還得留給第三次呼叫時使用

這些字元滿足先進先出,所以我們可以用一個Queue暫存這些字元.

需要用Queue儲存之前多讀的character。每次讀時,先看Queue裡的夠不夠,如果不夠,先讀到夠為止。

/* 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 Queue<Character> queue = new LinkedList<Character>();
    private boolean endOfFile = false;
     
    public int read(char[] buf, int n) {
        if(buf == null || n == 0) return 0;
        
        while(queue.size() < n && !endOfFile){
            char[] localbuf = new char[4];
            int localNum = read4(localbuf);
            if(localNum < 4) {
                endOfFile = true;
            }
            for(int i=0; i<localNum; i  ){
                queue.add(localbuf[i]);
            }
        }
        int size = Math.min(queue.size() , n);
        for(int i=0; i<size; i  ){
            buf[i] = queue.poll();
        }
        return size;
    }
}