java 158.读取N个字符给出Read4 II - 多次调用(1st).java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 158.读取N个字符给出Read4 II - 多次调用(1st).java相关的知识,希望对你有一定的参考价值。

/* 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
     */
    private Queue<Character> queue = new LinkedList<Character>();
    
    public int read(char[] buf, int n) {
        int cur = 0;
        char[] buf4 = new char[4];
        while (cur < n && !queue.isEmpty()) {
            buf[cur++] = queue.poll();
        }
        while (cur < n) {
            int remaining = read4(buf4);
            if (remaining == 0) break;
            int i = 0;
            for (i = 0; i < remaining && cur < n; i++) {
                buf[cur++] = buf4[i];
            }
            while (i < remaining) {
                queue.offer(buf4[i++]);
            }
        }
        return cur;
    }
}
/* 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
     */
    private char[] cache;
    private int curStart;
    private int curCount;
    public Solution() {
        this.cache = new char[4];
        this.curStart = 0;
        this.curCount = 0;
    }
    public int read(char[] buf, int n) {
        for (int i = 0; i < n; i++) {
            if (curStart == 0) {
                curCount = read4(cache);
            }
            if (curCount == 0) {
                return i;
            }
            buf[i] = cache[curStart++];
            if (curStart == curCount) {
                curStart = 0;
            }
        }
        return n;
    }
}

以上是关于java 158.读取N个字符给出Read4 II - 多次调用(1st).java的主要内容,如果未能解决你的问题,请参考以下文章

java 158.读取N个字符给出Read4 II - 多次调用(1st).java

java 158.读取N个字符给出Read4 II - 多次调用(1st).java

java 158.读取N个字符给出Read4 II - 多次调用(1st).java

java 158.读取N个字符给出Read4 II - 多次调用(1st).java

[leetcode]158. Read N Characters Given Read4 II - Call multiple times 用Read4读取N个字符2 - 调用多次

LeetCode 158: Read N Characters Given Read4 II