Do we need to consider the remaining characters?


  • 0
    J

    I am wondering why we don't need to consider the the remaining after every read. For example, there are 100 characters in a file. Each time we want to get 9 characters, so we call read(buf, 9).
    The first call reads 12 characters from the file and returns 9 to callers. So how to handle the remaining 3 characters? It seems impractical to discard them. If discard, next call will return 9 characters from position 13. I use a queue to buffer all the characters, but it looks like not necessary.

    public class Solution extends Reader4 {
        /**
         * @param buf Destination buffer
         * @param n   Maximum number of characters to read
         * @return    The number of characters read
         */
        Deque<Character> dq = new LinkedList();
        public int read(char[] buf, int n) {
            int size = 0, tempN = n;
            char [] temp = new char[4];
            while(tempN>0){
                size = read4(temp);
                for(int i=0; i<size; i++){
                    dq.offer(temp[i]);
                    tempN--;
                }
                if(size<4) break;
                if(dq.size()>=n) break;
            }
            int len = Math.min(n, dq.size());
            for(int i=0; i<len; i++){
                buf[i] = dq.pop();
            }
            return len;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.