题目链接:https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/
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.
思路:题意是说可能调用很多次,也就是说上次可能最后读入了4个,但是只取了2个,还剩了两个。所以要做一个标记,把上次读入了但是没有取走的字符串保留到这次。
我们可以做两个标记,一个上次剩余的长度,还有在数组中的位置,然后这个读入的时候先取上次读入的。
代码如下:
// Forward declaration of the read4 API. int read4(char *buf); class Solution { public: Solution():len(0), pos(0){} /** * @param buf Destination buffer * @param n Maximum number of characters to read * @return The number of characters read */ int read(char *buf, int n) { int tem = 0, offset = 0; while(n > 0 && len > 0) { buf[tem++] = str[pos++]; len--, n--, offset++; } while(n >0 && (tem=read4(str)) > 0) { len = tem>n?(tem-n):0; pos = (tem>n)?n:0; tem = min(tem, n); memcpy(buf+offset, str, tem); n -= tem; offset += tem; } return offset; } private: int len, pos; char str[4]; };