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.
Example 1:
Input: buf = "abc", n = 4
Output: "abc"
Explanation: The actual number of characters read is 3, which is "abc".
Example 2:
Input: buf = "abcde", n = 5
Output: "abcde"
Note:
The read
function will only be called once for each test case.
又是一道垃圾题目,连题干都是错的……
题目中说:
Input: buf = "abc", n = 4
Output: "abc"
Explanation: The actual number of characters read is 3, which is "abc".
完全是骗人的,真实情况是:
- 如果有一个
file = "abc"
,我们传入一个buf空数组:buf = ["", "", "", ..... ]
。
在调用完 read(buf, n)
之后(例如n=4),我们应该输出 output = 3
(读到了三个字符)。
而且buf
数组应该为:buf = ["a", "b", "c", "", "", "", …….]
- 如果调用
read(buf, n)
时n = 2
那么我们应该输出output = 2
(因为最多读取2个字符)。
而且buf
数组应该为:buf = ["a", "b", "", "", "", …….]
# The read4 API is already defined for you.
# @param buf, a list of characters
# @return an integer
# def read4(buf):
class Solution(object):
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)
if not length: # 如果文件中已经读不到字符,直接返回结果
return res
for i in range(min(length, n)): # 如果读取到字符且还没有达到n个,继续填充buf。
buf[res] = buf4[i]
res += 1
n -= 1
return res