Leetcode 158 Java solution with explanation

/**
 * 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   Number of characters to read
     * @return    The number of actual characters read
     */

    // we need to save unused characters in a queue
    // e.g. if we read 4 characters when calling read4, but we only need 2
    // we save the 2 remaining characters in remain, we can use the remaining 2 chars first
    // when next time the read(buf, n) is called
    Queue<Character> remain = new LinkedList<>();
 
    public int read(char[] buf, int n) {
        int i = 0;
        // check the remain queue first
        while (i < n && !remain.isEmpty()) {
            buf[i++] = remain.poll();
        }
        char[] temp = new char[4];
        while (i < n) {
           // call read4, return 4 or less characters
            int tmpCnt = read4(temp);
            int tmpIdx = 0;
            while (i < n && tmpIdx < tmpCnt) {
                buf[i++] = temp[tmpIdx++];
            }
           // if the tmpIdx < tmpCnt, means the i is equal to n, and there are remaining characters
           // need to store them in remain queue
            while (tmpIdx < tmpCnt) {
                remain.offer(temp[tmpIdx++]);
            }
            // the recent read4 return less than 4 characters, meaning reaching the end of the file
            if (tmpCnt < 4) {
                break;
            }
        }
        return i;
    }
}

Comments

Popular posts from this blog

Can I name a method with the same name of the class in Java?

What is new in Java 8

Quicksort Java implementation