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

這題和157一樣,提供read4 API,要寫read function。不同在於read可以被call很多次。

  • idea:  大致上和157相同,只差在eof要變成class的member, 並將一個queue加入class member,用來存read4後沒有寫入buf的character。 開始讀檔之前,先讀取queue裡面的字元,並在read4之後把沒存進buf的字元放進queue
  • pseudocode:

    read char from queue first
    
    while file not finish, and total < n,
        read4 into tmp,
        add 4 to total.
        if total read after read4 < n
            put into buffer
        else
            remainder = n-(total-4)
            total = n
            put remainder char into buf
            and put count-remainder char into queue
    
    return total
    
  • code:

    /* 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
         */
    
        //safe the characters that doesn't read into buf in last call
        Queue<Character> queue = new LinkedList<>();
        boolean eof = false;
    
        public int read(char[] buf, int n) {
            int total = 0;
            int idx = 0;
    
            //clear queue first
            while(!queue.isEmpty() && total < n){
                char c = queue.peek();
                queue.poll();
                buf[idx++] = c;
                total++;
            }
    
            while(!eof && total<n){
                char[] tmp = new char[4];
                int count = read4(tmp);
    
                if(count < 4) eof = true;
    
                total+=count;
                if(total < n){
                    for(int i=0; i<4; i++){
                        buf[idx++] = tmp[i];
                    }
                }else{
                    int remainder = n-(total-count);
                    total = n;
                    int i=0;
                    for(i=0; i<remainder; i++){
                        buf[idx++] = tmp[i];
                    }
                    //put the numbers left in tmp into queue
                    while(i<4 && remainder < count){
                        queue.offer(tmp[i]);
                        i++;
                        remainder++;
                    }
                }
            }
    
            return total;
        }
    }
    

results matching ""

    No results matching ""