LeetCode-Read N Characters Given Read4 II - Call multiple times

LiBlog發表於2016-08-30

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.

Solution:

 1 /* The read4 API is defined in the parent class Reader4.
 2       int read4(char[] buf); */
 3 
 4 public class Solution extends Reader4 {
 5     char[] tempBuf = new char[4];
 6     int offset = 4;
 7     int maxLen = 4;
 8 
 9     /**
10      * @param buf
11      *            Destination buffer
12      * @param n
13      *            Maximum number of characters to read
14      * @return The number of characters read
15      */
16     public int read(char[] buf, int n) {
17         int ind = 0;
18         while (offset < maxLen && ind < n) {
19             buf[ind++] = tempBuf[offset++];
20         }
21         if (maxLen < 4) return ind;
22         
23         ind = readFile(buf, ind, n);
24         return ind;
25     }
26 
27     public int readFile(char[] buf, int ind, int n) {
28         int num = 4;
29         while (num == 4 && ind < n) {
30             num = read4(tempBuf);
31             int end = Math.min(num, n - ind);
32             for (offset = 0; offset < end; offset++) {
33                 buf[ind++] = tempBuf[offset];
34             }
35         }
36         maxLen = num;
37         return ind;
38     }
39 }

 

相關文章