Read N Characters Given Read4 II - Call multiple times

题目

答案

关键是要管理好一块 4 bytes 的buffer,下一次call read的时候先从那块区域读取

public class Solution extends Reader4 {
    /**
     * @param buf Destination buffer
     * @param n   Maximum number of characters to read
     * @return    The number of characters read
     */

    int buf4_index = 0;
    int buf4_size = 0;
    char[] last_buf4 = new char[4];

    public int read(char[] buf, int n) {
        int total = 0;
        char[] buf4 = new char[4];

        // First, if there is anything left in last_buf4 unread, read it !
        if(buf4_size != 0) {
            for(int i = buf4_index; i < buf4_index + buf4_size && total < n; i++)
                buf[total++] = last_buf4[i];

            // Update unread number of chars left in last_buf4
            buf4_index += total;
            buf4_size -= total;
        }

        if(total == n) return n;

        // Now use read4 to read subsequent characters
        while(n > total) {
            int bytes_read = read4(buf4);
            // If what's read exceeds n, we will only take the part that we need
            if(total + bytes_read > n) {
                buf4_size = bytes_read - (n - total);
                bytes_read = n - total;
                buf4_index = bytes_read;
            }
            // Move data from buf4 to buf
            for(int i = 0; i < bytes_read; i++)
                buf[total++] = buf4[i];

            // End of File
            if(bytes_read < 4) break;
        }

        this.last_buf4 = buf4;
        return total;
    }
}

Same idea, but much more concise code

public class Solution extends Reader4 {
    int buf4_index = 0;
    int buf4_size = 0;
    char[] last_buf4 = new char[4];

    public int read(char[] buf, int n) {
        int total = 0;
        char[] buf4 = new char[4];

        while(total < n) {
            if(buf4_index < buf4_size) {
                buf[total++] = last_buf4[buf4_index++];
            }
            else {
                buf4_size = read4(last_buf4);
                buf4_index = 0;
                if(buf4_size == 0) break;
            }
        }
        return total;
    }
}

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