158. Read N Characters Given Read4 II - Call multiple times

Posted tobeabetterpig

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了158. Read N Characters Given Read4 II - Call multiple times相关的知识,希望对你有一定的参考价值。

158. Read N Characters Given Read4 II - Call multiple times




Given buf = "abc"
read("abc", 1) // returns "a"
read("abc", 2); // returns "bc"
read("abc", 1); // returns ""
Example 2: 

Given buf = "abc"
read("abc", 4) // returns "abc"
read("abc", 1); // returns ""

   

    private int buffPtr = 0;
    private int buffCnt = 0;
    private char[] buff = new char[4];
    public int read(char[] buf, int n) {
        int ptr = 0;
        while (ptr < n) {
            if (buffPtr == 0) {
                buffCnt = read4(buff);
            }
          
            if (buffCnt == 0) break;
          
            while (ptr < n && buffPtr < buffCnt) {
                buf[ptr++] = buff[buffPtr++];
            }
          
            if (buffPtr >= buffCnt){
              buffPtr = 0;
            }
        }
        return ptr;
    }
I used buffer pointer (buffPtr) and buffer Counter (buffCnt)
  to store the data received
in previous calls. In the while loop,
if buffPtr reaches current buffCnt, it will be set
as zero to be ready to read new data.

 

以上是关于158. Read N Characters Given Read4 II - Call multiple times的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 158: Read N Characters Given Read4 II - Call multiple times

[LeetCode] 158. Read N Characters Given Read4 II - Call multiple times

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

[Locked] Read N Characters Given Read4 & Read N Characters Given Read4 II - Call multiple times(

157. Read N Characters Given Read4

157. Read N Characters Given Read4