提纲:
157. Read N Characters Given Read4
158. Read N Characters Given Read4 II - Call multiple times
157. 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 reads n characters from the file.
Note:
The read function will only be called once for each test case.
思路(参考:https://segmentfault.com/a/1190000003794420):
用一个临时数组,存放每次read4读到字符,再用一个指针标记buf数组目前存储到的位置,然后将这个临时数组的内容存到buf相应的位置就行了。这里需要注意两个corner case:1. 如果本次读到多个字符,但是我们只需要其中一部分就能完成读取任务时,我们要拷贝的长度是本次读到的个数和剩余所需个数中较小的
2. 如果read4没有读满4个,说明数据已经读完,这时候对于读到的数据长度,因为也可能存在我们只需要其中一部分的情况,所以要返回总所需长度和目前已经读到的长度的较小的
/* The read4 API is defined in the parent class Reader4.
int read4(char[] buf); */
public class Solution extends Reader4 {
/**
* @param buf Destination buffer
* @param n Maximum number of characters to read
* @return The number of characters read
*/
public int read(char[] buf, int n) {
int total = 0;
char[] tmp = new char[4];
while (total < n) { // can write
int res = read4(tmp);
for (int i = 0; i < res && total < n; ++i) {
buf[total++] = tmp[i];
}
if (res != 4) {
// cannot read
break;
}
}
return total;
}
}
158. 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.
思路:难点是,如果上次因为total < n的限制没有写到文件但已经读进来的内容。下一次调用read的时候需要恢复。可以用先进先出的思路解决。
参考:https://segmentfault.com/a/1190000003794420
因为要调用多次,这里又多了一些corner case:
第一次调用时,如果read4读出的多余字符我们要先将其暂存起来,这样第二次调用时先读取这些暂存的字符
第二次调用时,如果连暂存字符都没读完,那么这些暂存字符还得留给第三次调用时使用
所以,难点就在于怎么处理这个暂存字符。因为用数组和指针控制对第二种情况比较麻烦,且这些字符满足先进先出,所以我们可以用一个队列暂存这些字符。这样,只要队列不为空,就先读取队列。
public class Solution extends Reader4 {
Queue<Character> buffer = new LinkedList<>();
/**
* @param buf Destination buffer
* @param n Maximum number of characters to read
* @return The number of characters read
*/
public int read(char[] buf, int n) {
int total = 0;
char[] tmp = new char[4];
while (buffer.isEmpty() == false && total < n) {
buf[total++] = buffer.poll();
}
while (total < n) {
int res = read4(tmp);
for (int i = 0; i < res; ++i) {
if (total >= n) {
buffer.offer(tmp[i]);
} else {
buf[total++] = tmp[i];
}
}
if (res != 4) {
break;
}
}
return total;
}
}