码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-08-30 07:05:28      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

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 }

 

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

标签:

原文地址:http://www.cnblogs.com/lishiblog/p/5820382.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!