题目:
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.
思路:
建议读者将这道题目和Leetcode 157结合起来思考。它和Leetcode 157的不同之处就在于read(char *buf, int n)方法可能被调用多次,这样就产生了一个问题:上一次调用时读到buffer中的内容可能没有被取尽,所以下次调用read方法时,需要优先从上次没有读完的buffer中读取数据。所以,我们需要在类中记录三个类变量:长度为4的缓冲区(buffer),有效长度(last_length)以及起始位置(last_pos)。每次在调用read(char *buf, int n)的时候,我们首先从buffer中读取剩余数据;然后再调用read4这一API从文件中读取数据(这一部分的思路就和Leetcode 157完全一样了)。
代码:
// Forward declaration of the read4 API.
int read4(char *buf);
class Solution {
public:
/**
* @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 ret = 0;
while(last_pos < last_length && n-- > 0) { // read the left charachters from last time
buf[ret++] = buffer[last_pos++];
}
while(n > 0) {
last_length = read4(buffer);
if(last_length == 0) {
return ret;
}
last_pos = 0;
while(last_pos < last_length && n-- > 0) { // read the current chacters until read over or the read length reaches n
buf[ret++] = buffer[last_pos++];
}
}
return ret;
}
private:
int last_pos = 0, last_length = 0;
char buffer[4];
};