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

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

时间:2018-01-28 11:11:10      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:queue   []   fun   deque   int   enqueue   div   reads   var   

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

标签:queue   []   fun   deque   int   enqueue   div   reads   var   

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

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