系统操作模拟实现
157. Read N Characters Given Read4
参考了这个帖子.
特别注意input是"leetcode", 5
的情况,output是leetc
而不是leetcode
,所以要注意index和n的比较。
/**
* 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 Number of characters to read
* @return The number of actual characters read
*/
public int read(char[] buf, int n) {
boolean endOfFile = false;
int i = 0;
while (i < n && !endOfFile) {
char[] temp = new char[4];
int read4 = read4(temp);
if (read4 != 4) {
endOfFile = true;
}
int len = Math.min(read4, n - i);
for (int j = 0; j < len; j++) {
buf[i++] = temp[j];
}
}
return i;
}
}