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

Posted Keep walking

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 158: Read N Characters Given Read4 II - Call multiple times相关的知识,希望对你有一定的参考价值。

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      * @param buf Destination buffer
 7      * @param n   Maximum number of characters to read
 8      * @return    The number of characters read
 9      */
10     
11     private Queue<char> buffer = new Queue<char>();
12     
13     public int Read(char[] buf, int n) {
14         // try to read from buffer
15         int i = 0;
16         while (i < n && buffer.Count > 0)
17         {
18             buf[i++] = buffer.Dequeue();
19         }
20         
21         // try to read from file
22         bool eof = false;        
23         while (i < n && !eof)
24         {
25             var temp = new char[4];
26             int r = Read4(temp);
27             
28             if (r < 4)
29             {
30                 eof = true;
31             }
32             
33             for (int k = 0; k < r; k++)
34             {
35                 if (i >= n) 
36                 {
37                     // save the left into the buffer
38                     buffer.Enqueue(temp[k]);                
39                 }
40                 else
41                 {
42                     buf[i++] = temp[k];
43                 }
44             }
45         }
46         
47         return i;
48     }
49 }

 


以上是关于Leetcode 158: Read N Characters Given Read4 II - Call multiple times的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 158. Read N Characters Given Read4 II - Call multiple times

[leetcode]158. Read N Characters Given Read4 II - Call multiple times 用Read4读取N个字符2 - 调用多次

158. Read N Characters Given Read4 II - Call multiple times

java 158.读取N个字符给出Read4 II - 多次调用(1st).java

java 158.读取N个字符给出Read4 II - 多次调用(1st).java

java 158.读取N个字符给出Read4 II - 多次调用(1st).java