My code:
/* The read4 API is defined in the parent class Reader4.
int read4(char[] buf); */
public class Solution extends Reader4 {
Queue<Character> q = new LinkedList<Character>();
/**
* @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) {
char[] arr = new char[4];
int counter = 0;
int num = 4;
while (num == 4 && counter < n) {
while (!q.isEmpty() && counter < n) {
buf[counter] = q.poll();
counter++;
}
if (counter >= n) {
return counter;
}
num = read4(arr);
int rightMost = Math.min(counter + num, n);
for (int i = counter; i < rightMost; i++) {
buf[i] = arr[i - counter];
}
if (counter + num > n) {
for (int i = n; i < counter + num; i++) {
q.offer(arr[i - counter]);
}
}
counter = Math.min(counter + num, n);
}
return counter;
}
}
自己做了出来。其实还好。看懂题意就简单多了。
用 Queue 来存储读多了的字符,下次用。
Anyway, Good luck, Richardo! — 09/20/2016