首页 > 其他 > 详细

LeetCode – Refresh – Read N Characters Given Read4 II

时间:2015-03-22 16:17:50      阅读:153      评论:0      收藏:0      [点我收藏+]

Since it need to record the previous chars, we just have to maintain a queue. Actually, the number of left chars are no larger than 4.

 

 1 // Forward declaration of the read4 API.
 2 int read4(char *buf);
 3 
 4 class Solution {
 5 private:
 6     queue<char> container;
 7 public:
 8     /**
 9      * @param buf Destination buffer
10      * @param n   Maximum number of characters to read
11      * @return    The number of characters read
12      */
13     int read(char *buf, int n) {
14         int len = 0, each = INT_MAX;
15         while (!container.empty()) {
16             *buf = container.front();
17             container.pop();
18             buf++;
19             len++;
20         }
21         while (len < n && (each = read4(buf))) {
22             len += each;
23             buf += each;
24         }
25         if (len >= n) {
26             for (int i = 0; i < len - n; i++) {
27                 container.push(buf[n-len+i]);
28             }
29             buf[n-len] = \0;
30             len = n;
31         }
32         return len;
33     }
34 };

 

LeetCode – Refresh – Read N Characters Given Read4 II

原文:http://www.cnblogs.com/shuashuashua/p/4357405.html

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