难度: Easy
原题连接
内容描述
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.
思路 1
讨论区有很多人说这道题很sb,给的例子和代码里面的input数据类型不一样,其实我也很懵逼 然后我看到了这个解释,顿悟
It took me several hours to understand what the problem is talking about.
Let's look at the very first sentence of the description, "The API: int read4(char *buf) reads 4 characters at a time from a file." I though this function read a file, which is represented by *buf. But I was wrong. The correct understanding should be like this: this function reads a file, and writes the first 4 characters to *buf, and if there are less than 4 characters to be read, then only the valid number of characters will be read and written to *buf.
Similarly, the function to be implemented, int read(char buf, int n) that reads n characters from the file, means n characters should be written to *buf.
Also the examples are very misleading. Let's say example 1,
Input: buf = "abc", n = 4
Output: "abc"
Explanation: The actual number of characters read is 3, which is "abc".
The input *buf is not "abc". The file to be read is "abc". The input, *buf , should be where the characters are written to. The output, is not the return value of read(buf, 4), but should be the actual characters in *buf after the function is called. And the return value should be an int, which is 3.
Hope this clarification helps :)
总结一下,就是read4(*read4_buf)
这个函数的意思就是从文件当中读4个字符并将其写入到read4_buf中去,返回值是实际读取到的字符个数,即如果文件中只剩3个(不到4个字符了)
,那么就只写3个字符到read4_buf中去,返回值是3
所以我们要实现的read(*buf)函数也是这样,我们要读取n个字符并写入到buf中去并且返回实际读取到的字符个数,如果不够我们就有多少写多少,然后返回实际写入的个数
那么现在我们有两种情况:
- n大于文件中的字符数,我们检测文件结束并停止读取并返回文件中的字符数。
- n小于或等于文件中的字符数,当读取足够的字符时返回(即n)
代码中用eof代表'end of file'
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)
"""
if n == 0 :
return 0
total_read, eof = 0, False
while not eof:
read4_buf = [''] * 4
cur_read = read4(read4_buf)
if (cur_read < 4):
eof = True
for i in range(cur_read):
buf[total_read] = read4_buf[i]
total_read += 1
if total_read == n:
return total_read
return total_read