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.

解题思路:

讲真这道题我读题的时候就一脸懵逼。

他给的例子中描述了当字符串长度<=n的情况。

但是也有字符串长度>n的情况

我们还要考虑空字符串的情况(这些都是我试出来的ಠ_ಠ

我们有total来存储当前读到的字符个数,用num来存储当前用read4读到的字符个数。

如果num = 0 说明字符个数小于n这时候我们可以直接返回num。

需要注意的是:要移动指针。

代码:

// Forward declaration of the read4 API.
int read4(char *buf);

class Solution {
public:
    /**
     * @param buf Destination buffer
     * @param n   Maximum number of characters to read
     * @return    The number of characters read
     */
    int read(char *buf, int n) {
        int total = 0;
        while(total < n){
            int num = read4(buf);
            total += num;
            buf += num;
            if(num == 0)
                return total;
        }
        return total > n ? n : total;
    }
};

猜你喜欢

转载自www.cnblogs.com/yaoyudadudu/p/9194371.html
今日推荐