首页 > 其他 > 详细

Leetcode 158: Read N Characters Given Read4 II - Call multiple times

时间:2018-01-28 10:41:45      阅读:232      评论: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.

 

 1 /* The Read4 API is defined in the parent class Reader4.
 2       int Read4(char[] buf); */
 3 
 4 public class Solution : Reader4 {
 5     
 6     private Queue<char> queue = new Queue<char>();
 7     
 8     /**
 9      * @param buf Destination buffer
10      * @param n   Maximum number of characters to read
11      * @return    The number of characters read
12      */
13     public int Read(char[] buf, int n) {
14         int count = 0;
15         
16         while (count < n)
17         {
18             while (queue.Count > 0)
19             {
20                 buf[count++] = queue.Dequeue();
21                 
22                 if (count == n)
23                 {
24                     return count;
25                 }
26             }
27             
28             var newBuf = new char[4];
29             int total = Read4(newBuf);
30             
31             if (total == 0)
32             {
33                 // eof condtion
34                 break;
35             }
36             
37             // read into queue
38             for (int i = 0; i < total; i++)
39             {
40                 queue.Enqueue(newBuf[i]);
41             }
42         }
43         
44         return count;
45     }
46 }

 

Leetcode 158: Read N Characters Given Read4 II - Call multiple times

原文:https://www.cnblogs.com/liangmou/p/8369536.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!