157. Read N Characters Given Read4 最长有效括号
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.
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 :)
代码中用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