[Locked] Read N Characters Given Read4 & Read N Characters Given Read4 II - Call multiple times
Read N Characters Given Read4
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 readsn characters from the file.
Note:
The read
function will only be called once for each test case.
分析:
read函数被调用一次,那么就直接用代码解释这题即可吧。
代码:
int read4(char *buf); class Solution { public: int read(char *buf, int n) { char *cur = buf; int clen = 0, slen = 0; //当还有字符可以读出来时 while((clen = read4(cur))) { slen += clen; //当字符数目超出n时,只留下n个 if(slen >= n) { cur += n + 4 - slen; break; } cur += clen; } *cur = '\0'; //当字符数目小于n时,文件就读完了,则返回文件总长;若字符数目大于等于n时,返回n return slen < n ? slen : n; } };
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.
分析:
相比于I,这题要被调用多次,而大量的文件读取操作时间代价很大,为了解决这个问题,可以用一个缓存存储已经读过的字符,我用一个私有的string作为缓存。
代码:
int read4(char *buf); class Solution { private: string str; public: Solution() { str = ""; } int read(char *buf, int n) { //利用缓存除去不必要的操作 if(n <= str.length()) { //将string传给字符串数组 strncpy(buf, str.c_str(), n); return n; } strcpy(buf, str.c_str()); char *cur = buf + str.length(); int clen = 0, slen = int(str.length()); //当缓存不够用时,继续在文件里读取字符 while((clen = read4(cur))) { slen += clen; //当字符数目超出n时,只留下n个 if(slen >= n) { str.append(cur, n + 4 - slen); cur += n + 4 - slen; break; } //字符串数组传给string str.append(cur, clen); cur += clen; } *cur = '\0'; //当字符数目小于n时,文件就读完了,则返回文件总长;若字符数目大于等于n时,返回n return slen < n ? slen : n; } };
注:本题代码没有验证