157. Read N Characters Given Read4

Posted yaoyudadudu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
    }
};

 


以上是关于157. Read N Characters Given Read4的主要内容,如果未能解决你的问题,请参考以下文章

157 Read N Characters Given Read4

157. Read N Characters Given Read4

Leetcode 157: Read N Characters Given Read4

leetcode 157. Read N Characters Given Read4 利用read4实现read --------- java

[Locked] Read N Characters Given Read4 & Read N Characters Given Read4 II - Call multiple times(

[leetcode]Read N Characters Given Read4