美文网首页
二刷157. Read N Characters Given R

二刷157. Read N Characters Given R

作者: greatseniorsde | 来源:发表于2018-02-03 11:03 被阅读0次

这个题感觉之前还是没完全理解题意,比如我们的字节流是abcdefghij, 我们调用read4, 那么read4(char[] temp)这个函数里,会依次返回4,4,2, 而temp会分别为abcd, efgh, ij, 通过调用read4来实现read, 这里的read(char[] buf, int n)里的buf就相当于read4的temp, n表示最大的可以读进去的数量(类比于read4里面的4)

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

    public int read(char[] buf, int n) {
        char[] temp = new char[4];
        int index = 0;
        while (true){
            int count = read4(temp);
            //n - index = 还剩下要读的char数
            count = Math.min(count, n - index);
            for (int i = 0; i < count; i++){
                buf[index++] = temp[i];
            }
            //index == 4 : reached the max that can be read
            //count < 4 : readched the end of the text stream
            if (index == n || count < 4){
                return index;
            }
        }
    }
}

相关文章

网友评论

      本文标题:二刷157. Read N Characters Given R

      本文链接:https://www.haomeiwen.com/subject/xmfuzxtx.html