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.
Example 1:
Given buf = "abc"
read("abc", 1) // returns "a"
read("abc", 2); // returns "bc"
read("abc", 1); // returns ""
Example 2:
Given buf = "abc"
read("abc", 4) // returns "abc"
read("abc", 1); // returns ""
这道题和上一次道题不一样的是,多次进行读取,那么问题就来了:
-
每一次调用
read4
取四个字符,如果调用read
时只读了两个(还剩下两个未读到),那么下次再调用read
时,之前剩下的那两个还要吗?答案是:要的。所以必须保存之前的状态。我们可以做一个缓冲区
self.arr
,把每次调用read4
读取的字符都放到这里面,调用read
时,被读到的字符就pop掉。这样一来,未读到的字符永远不会丢失。
# The read4 API is already defined for you.
# @param buf, a list of characters
# @return an integer
# def read4(buf):
class Solution(object):
def __init__(self):
self.arr=[]
def read(self, buf, n):
"""
:type buf: Destination buffer (List[str])
:type n: Maximum number of characters to read (int)
:rtype: The number of characters read (int)
"""
res = 0
while n > 0:
buf4 = [""] * 4
length = read4(buf4) # 这里的length下面用不到了,因为使用的是self.arr的长度。
self.arr += buf4 # 将读到的字符放到self.arr中。
if len(self.arr) == 0:
return res
for i in range(min(len(self.arr), n)): # 如果self.arr中有字符且还没有达到n个,继续填充buf。
buf[res] = self.arr.pop(0) # 此时是从self.arr中取字符。
res += 1
n -= 1
return res