/* 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
*/
private Queue<Character> queue = new LinkedList<Character>();
public int read(char[] buf, int n) {
int cur = 0;
char[] buf4 = new char[4];
while (cur < n && !queue.isEmpty()) {
buf[cur++] = queue.poll();
}
while (cur < n) {
int remaining = read4(buf4);
if (remaining == 0) break;
int i = 0;
for (i = 0; i < remaining && cur < n; i++) {
buf[cur++] = buf4[i];
}
while (i < remaining) {
queue.offer(buf4[i++]);
}
}
return cur;
}
}
/* 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
*/
private char[] cache;
private int curStart;
private int curCount;
public Solution() {
this.cache = new char[4];
this.curStart = 0;
this.curCount = 0;
}
public int read(char[] buf, int n) {
for (int i = 0; i < n; i++) {
if (curStart == 0) {
curCount = read4(cache);
}
if (curCount == 0) {
return i;
}
buf[i] = cache[curStart++];
if (curStart == curCount) {
curStart = 0;
}
}
return n;
}
}