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
The
read
function may be called multiple times./* The read4 API is defined in the parent class Reader4. int read4(char[] buf); */ public class Solution extends Reader4 { Queuequeue = new LinkedList (); public int read(char[] buf, int n) { int i = 0; while (i < n && !queue.isEmpty()) { buf[i] = queue.poll(); i++; } for (; i < n; i+= 4) { char[] tem = new char[4]; int len = read4(tem); if (len > n - i) { System.arraycopy(tem, 0, buf, i, n - i); for (int j = n - i; j < len; j++) { queue.offer(tem[j]); } } else { System.arraycopy(tem, 0, buf, i, len); } if (len < 4) { return Math.min(len + i, n); } } return n; } }
没有评论:
发表评论