[LeetCode] Read N Characters Given Read4 用Read4来读取N个字符

简介:

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.

这道题给了我们一个Read4函数,每次可以从一个文件中最多读出4个字符,如果文件中的字符不足4个字符时,返回准确的当前剩余的字符数。现在让我们实现一个最多能读取n个字符的函数。这题有迭代和递归的两种解法,我们先来看迭代的方法,思路是我们每4个读一次,然后把读出的结果判断一下,如果为0的话,说明此时的buf已经被读完,跳出循环,直接返回res和n之中的较小值。否则一直读入,直到读完n个字符,循环结束,最后再返回res和n之中的较小值,参见代码如下:

解法一:

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

class Solution {
public:
    int read(char *buf, int n) {
        int res = 0;
        for (int i = 0; i <= n / 4; ++i) {
            int cur = read4(buf + res);
            if (cur == 0) break;
            res += cur;
        }
        return min(res, n);
    }
};

下面来看递归的解法,这个也不难,我们对buf调用read4函数,然后判断返回值t,如果返回值t大于等于n,说明此时n不大于4,直接返回n即可,如果此返回值t小于4,直接返回t即可,如果都不是,则直接返回调用递归函数加上4,其中递归函数的buf应往后推4个字符,此时n变成n-4即可,参见代码如下:

解法二:

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

class Solution {
public:
    int read(char *buf, int n) {
        int t = read4(buf);
        if (t >= n) return n;
        if (t < 4) return t;
        return 4 + read(&buf[4], n - 4);
    }
};

本文转自博客园Grandyang的博客,原文链接:用Read4来读取N个字符[LeetCode] Read N Characters Given Read4 ,如需转载请自行联系原博主。

相关文章
|
4月前
|
存储 算法 程序员
【Leetcode 程序员面试金典 01.01】判定字符是否唯一 —— 位运算|哈希表
可以使用哈希表或位运算来解决此问题:由题可知s[i]仅包含小写字母,int[26]即能表示字符的出现次数;
|
2月前
|
网络协议
《 LeetCode 热题 HOT 100》——无重复字符的最长子串
《 LeetCode 热题 HOT 100》——无重复字符的最长子串
|
3月前
|
存储 算法 Go
LeetCode 第三题: 无重复字符的最长子串
  给定一个字符串,请你找出其中不含有重复字符的最长子串的长度。
|
4月前
【Leetcode 2707】字符串中的额外字符 —— 动态规划
1. 状态定义:把`s[i−1]`当做是额外字符,`d[i] = d[i−1] + 1` 2. 状态转移方程:遍历所有的`j(j∈[0,i−1])`,如果子字符串`s[j...i−1]`存在于`dictionary`中,那么`d[i] = min d[j] 3. 初始状态`d[0] = 0`,最终答案为`d[n]`
|
4月前
leetcode:3. 无重复字符的最长子串
leetcode:3. 无重复字符的最长子串
16 0
|
4月前
|
算法
leetcode:387. 字符串中的第一个唯一字符
leetcode:387. 字符串中的第一个唯一字符
13 0
|
2月前
|
机器学习/深度学习 算法
力扣刷题日常(一)
力扣刷题日常(一)
20 2
|
2月前
|
存储 索引
《LeetCode》—— LeetCode刷题日记
《LeetCode》—— LeetCode刷题日记
|
2月前
|
搜索推荐
《LeetCode》——LeetCode刷题日记3
《LeetCode》——LeetCode刷题日记3

热门文章

最新文章