158. 用 Read4 读取 N 个字符 II

匿名 (未验证) 提交于 2019-12-02 23:54:01

read 方法:

返回值为实际读取的字符。

参数: char[] buf, int n
返回值: int

注意: buf[] 是目标缓存区不是源缓存区,你需要将结果写入 buf[] 中。

示例 1:

File file("abc");
Solution sol;
// 假定 buf 已经被分配了内存,并且有足够的空间来存储文件中的所有字符。
sol.read(buf, 1); // 当调用了您的 read 方法后,buf 需要包含 "a"。 一共读取 1 个字符,因此返回 1。
sol.read(buf, 2); // 现在 buf 需要包含 "bc"。一共读取 2 个字符,因此返回 2。
sol.read(buf, 1); // 由于已经到达了文件末尾,没有更多的字符可以读取,因此返回 0。
Example 2:

File file("abc");
Solution sol;
sol.read(buf, 4); // 当调用了您的 read 方法后,buf 需要包含 "abc"。 一共只能读取 3 个字符,因此返回 3。
sol.read(buf, 1); // 由于已经到达了文件末尾,没有更多的字符可以读取,因此返回 0。
注意:

你 不能 直接操作该文件,文件只能通过 read4 获取而 不能 通过 read。



保证在一个给定测试用例中,read 函数使用的是同一个 buf。

Solution:

和上一题的区别是会多次调用这个函数,用静态变量记录当前读取的状态(读取的idx,cur字符数和temp数据)即可。每4个读一次,更新idx=0再继续读。

""" The read4 API is already defined for you.      @param buf, a list of characters     @return an integer     def read4(buf):  # Below is an example of how the read4 API can be called. file = File("abcdefghijk") # File is "abcdefghijk", initially file pointer (fp) points to 'a' buf = [' '] * 4 # Create buffer with enough space to store characters read4(buf) # read4 returns 4. Now buf = ['a','b','c','d'], fp points to 'e' read4(buf) # read4 returns 4. Now buf = ['e','f','g','h'], fp points to 'i' read4(buf) # read4 returns 3. Now buf = ['i','j','k',...], fp points to end of file """ class Solution(object):     idx = 0     cur = 0     temp = [' '] * 4     def read(self, buf, n):         """         :type buf: Destination buffer (List[str])         :type n: Number of characters to read (int)         :rtype: The number of actual characters read (int)         """         start = 0         while start < n:             if not Solution.idx: Solution.cur = read4(Solution.temp)             if not Solution.cur: break             # 没有超过4个             while start < n and Solution.idx < Solution.cur:                 buf[start] = Solution.temp[Solution.idx]                 start += 1                 Solution.idx += 1             # 每4个读一次             if Solution.idx >= Solution.cur: Solution.idx = 0                      return start      

来源: https://www.cnblogs.com/lowkeysingsing/p/11361473.html

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!