[LeetCode] Read N Characters Given Read4 II - Call multiple times 用Read4来读取N个字符之二 - 多次调用

 

The API: int read4(char *buf) reads 4 characters at a time from a file.

The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file.

By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.

Note:
The read function may be called multiple times.

 

这道题是之前那道Read N Characters Given Read4的拓展,那道题说read函数只能调用一次,而这道题说read函数可以调用多次,那么难度就增加了,为了更简单直观的说明问题,我们举个简单的例子吧,比如:

buf = "abcdefgh"

那么我们如果调用read(buf, 3)的话,如果用之前那题的方法调用,直接读4个,那么读出来"abcd”了后buf变成"efgh",如果我们再想调用read(buf, 3),就只能从e开始读了,原来的d就失踪了,所以这题的核心就是如何保存那些不应该丢失的字符。我们需要内置一个buff数组,大小为5,我们最开始先从buf中读出4个字符,然后将前3个存入buff数组中,此时buff中为a,b,c。

然后我们调用第二个read(buf, 3),此时cnt重置为0,buffCnt为4,buffPtr为3,此时我们更新buff[0] = 'd',然后此时buffPtr重置为0,我们需要用read4来重新读取4个字符,我们要将buf右移上次调用read4的结果buffCnt,此时buf变为"efgh",从这里读取4个,由于n=3,所以buff中为d,e,f。

 

// Forward declaration of the read4 API.
int read4(char *buf);

class Solution {
public:
    Solution(): buffCnt(0), buffPtr(0) {}
    int read(char *buf, int n) {
        int cnt = 0;
        while (cnt < n) {
            if (buffPtr == 0) {
         buf += buffCnt;
         buffCnt = read4(buf);
       }
if (buffCnt == 0) break; while (cnt < n && buffPtr < buffCnt) { buff[cnt++] = buf[buffPtr++]; } if (buffPtr == buffCnt) buffPtr = 0; } return cnt; } private: int buffCnt, buffPtr; char buff[5]; };

 

类似题目:

Read N Characters Given Read4

 

参考资料:

https://leetcode.com/discuss/21219/a-simple-java-code

 

LeetCode All in One 题目讲解汇总(持续更新中...)

你可能感兴趣的:([LeetCode] Read N Characters Given Read4 II - Call multiple times 用Read4来读取N个字符之二 - 多次调用)