Read N Characters Given Read4 – LeetCode 157
Problem
Description
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 will only be called once for each test case.
Answer
Original
Code
1 | // Forward declaration of the read4 API. |
思路
简单的循环读取,如果提早结束了就判断并返回,在n不是4的倍数但文件大小大于n时会存在信息泄露的安全风险,不过胜在逻辑清晰。时间复杂度$O(n)$,空间复杂度$O(1)$。
Better
还没看到更好的思路。