C++实现LeetCode(157.用Read4来读取N个字符)

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

Given a file and assume that you can only read the file using a given method read4, implement a method to read n characters.

Method read4:

The API read4 reads 4 consecutive characters from the file, then writes those characters into the buffer array buf.

The return value is the number of actual characters read.

Note that read4() has its own file pointer, much like FILE *fp in C.

Definition of read4:

    Parameter:  char[] buf
Returns:    int

Note: buf[] is destination not source, the results from read4 will be copied to buf[]

Below is a high level example of how read4 works:

File file("abcdefghijk"); // File is "abcdefghijk", initially file pointer (fp) points to 'a'
char[] buf = new char[4]; // Create buffer with enough space to store characters
read4(buf); // read4 returns 4. Now buf = "abcd", fp points to 'e'
read4(buf); // read4 returns 4. Now buf = "efgh", fp points to 'i'
read4(buf); // read4 returns 3. Now buf = "ijk", fp points to end of file

Method read:

By using the read4 method, implement the method read that reads n characters from the file and store it in the buffer array buf. Consider that you cannot manipulate the file directly.

The return value is the number of actual characters read.

Definition of read:

    Parameters: char[] buf, int n
Returns: int

Note: buf[] is destination not source, you will need to write the results to buf[]

Example 1:

Input: file = "abc", n = 4
Output: 3
Explanation: After calling your read method, buf should contain "abc". We read a total of 3 characters from the file, so return 3. Note that "abc" is the file's content, not buf. buf is the destination buffer that you will have to write the results to.

Example 2:

Input: file = "abcde", n = 5
Output: 5
Explanation: After calling your read method, buf should contain "abcde". We read a total of 5 characters from the file, so return 5.

Example 3:

Input: file = "abcdABCD1234", n = 12
Output: 12
Explanation: After calling your read method, buf should contain "abcdABCD1234". We read a total of 12 characters from the file, so return 12.

Example 4:

Input: file = "leetcode", n = 5
Output: 5
Explanation: After calling your read method, buf should contain "leetc". We read a total of 5 characters from the file, so return 5.

Note:

  1. Consider that you cannot manipulate the file directly, the file is only accesible for read4 but not for read.
  2. The read function will only be called once for each test case.
  3. You may assume the destination buffer array, buf, is guaranteed to have enough space for storing n characters.

这道题给了我们一个 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);
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/157

类似题目:

Read N Characters Given Read4 II - Call multiple times

参考资料:

https://leetcode.com/problems/read-n-characters-given-read4/

https://leetcode.com/problems/read-n-characters-given-read4/discuss/49557/Accepted-clean-java-solution

https://leetcode.com/problems/read-n-characters-given-read4/discuss/49496/Another-accepted-Java-solution

到此这篇关于C++实现LeetCode(157.用Read4来读取N个字符)的文章就介绍到这了,更多相关C++实现用Read4来读取N个字符内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • C++实现LeetCode(151.翻转字符串中的单词)

    [LeetCode] 151.Reverse Words in a String 翻转字符串中的单词 Given an input string, reverse the string word by word. For example, Given s = "the sky is blue", return "blue is sky the". Update (2015-02-12): For C programmers: Try to solve it in-p

  • C++实现LeetCode(158.用Read4来读取N个字符之二 - 多次调用)

    [LeetCode] 158. Read N Characters Given Read4 II - Call multiple times 用Read4来读取N个字符之二 - 多次调用 Given a file and assume that you can only read the file using a given method read4, implement a method read to read n characters. Your method read may be ca

  • C++实现LeetCode(154.寻找旋转有序数组的最小值之二)

    [LeetCode] 154. Find Minimum in Rotated Sorted Array II 寻找旋转有序数组的最小值之二 Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e.,  [0,1,2,4,5,6,7] might become  [4,5,6,7,0,1,2]). Find the minimum element. Th

  • C++实现LeetCode(153.寻找旋转有序数组的最小值)

    [LeetCode] 153. Find Minimum in Rotated Sorted Array 寻找旋转有序数组的最小值 Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e.,  [0,1,2,4,5,6,7] might become  [4,5,6,7,0,1,2]). Find the minimum element. You may

  • C++实现LeetCode(155.最小栈)

    [LeetCode] 155. Min Stack 最小栈 Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top element. getM

  • C++实现LeetCode(152.求最大子数组乘积)

    [LeetCode] 152. Maximum Product Subarray 求最大子数组乘积 Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product. Example 1: Input: [2,3,-2,4] Output: 6 Explanation: [2,3] has

  • C++实现LeetCode(159.最多有两个不同字符的最长子串)

    [LeetCode] 159. Longest Substring with At Most Two Distinct Characters 最多有两个不同字符的最长子串 Given a string s , find the length of the longest substring t  that contains at most 2 distinct characters. Example 1: Input: "eceba" Output: 3 Explanation: ti

  • C++实现LeetCode(156.二叉树的上下颠倒)

    [LeetCode] 156. Binary Tree Upside Down 二叉树的上下颠倒 Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the origina

  • C++实现LeetCode(157.用Read4来读取N个字符)

    [LeetCode] 157. Read N Characters Given Read4 用Read4来读取N个字符 Given a file and assume that you can only read the file using a given method read4, implement a method to read n characters. Method read4: The API read4 reads 4 consecutive characters from t

  • 读取带敏感字符的行的批处理

    复制代码 代码如下: @echo off :: 普通的 for+findstr 语句会忽略分号开头的行 :: findstr /n .* 用delims=:后,会忽略行首所有的冒号 :: 还有!.&..等特殊符号需要处理 :: 以下代码可以准确提取这些敏感字符 :: 解决了 setlocal 最大递归层的问题(setlocal 两两嵌套处理超过15行内容时会带来此问题) :: 能计算空行 :: code by jm 2006-12-12 thanks 3742668 CMD@XP set num

  • PHPExcel读取Excel文件的实现代码

    涉及知识点: php对excel文件进行循环读取 php对字符进行ascii编码转化,将字符转为十进制数 php对excel日期格式读取,并进行显示转化 php对汉字乱码进行编码转化 复制代码 代码如下: <?php require_once 'PHPExcel.php'; /**对excel里的日期进行格式转化*/ function GetData($val){ $jd = GregorianToJD(1, 1, 1970); $gregorian = JDToGregorian($jd+in

  • PHP文件读取功能的应用实例

    PHP文件读取操作相对于文件写入操作涉及更多的PHP文件操作函数,在代码实例中会详细介绍这些函数. 读取文本文件中存储数据的方式主要涉及的三个步骤及部分文件操作函数如下: 1.打开文件(文件操作函数:fopen) 2.文件数据读取(文件操作函数:fgets.file.readfile.feof等) 3.关闭文件(文件操作函数:fclose) 下面仍然以PHP文件读写操作代码实例讲解文件读取方法的具体应用,在实例中,通过调用不同的PHP文件读取操作函数读取文本文件中的数据,你可以加深PHP文件读取

  • PHP文件读写操作之文件读取方法详解

    PHP文件读取操作相对于文件写入操作涉及更多的PHP文件操作函数,在代码实例中会详细介绍这些函数. 读取文本文件中存储数据的方式主要涉及的三个步骤及部分文件操作函数如下: 1.打开文件(文件操作函数:fopen) 2.文件数据读取(文件操作函数:fgets.file.readfile.feof等) 3.关闭文件(文件操作函数:fclose) 下面仍然以PHP文件读写操作代码实例讲解文件读取方法的具体应用,在实例中,通过调用不同的PHP文件读取操作函数读取文本文件中的数据,你可以加深PHP文件读取

  • 用C语言实现从文本文件中读取数据后进行排序的功能

    功能介绍 程序的功能是从外部读取一个包括int型数据的文本文件,然后将它保存到内部临时数组,对数组进行排序后,以文本形式输出到指定的文件上.因为是int类型的数据,没有很严重的损失精度的问题. 正常运行要求: 包括数据的源文件内不能包括其他任何除数字和空白字符(空格,制表符,换行符)之外的任何字符,源文件最开始必须是数字字符,要保证源文件的数据计数正确.同时保证文件名有效. 运行结果 data.txt: obj.txt: 完整代码 警告:版权所有,谨供参考! #include <stdio.h>

  • Python read函数按字节(字符)读取文件的实现

    文件对象提供了 read() 方法来按字节或字符读取文件内容,到底是读取宇节还是字符,则取决于是否使用了 b 模式,如果使用了 b 模式,则每次读取一个字节:如果没有使用 b 模式,则每次读取一个字符.在调用该方法时可传入一个整数作为参数,用于指定最多读取多少个字节或宇符. 例如,如下程序采用循环读取整个文件的内容: f = open("read_test.py", 'r', True) while True: # 每次读取一个字符 ch = f.read(1) # 如果没有读到数据,

  • c读取一行字符串,以及c++读取一行字符串的实例

    一 c读取一行字符串 1 gets #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { int size = 1024; char* buff = (char*)malloc(size); // read lines while(NULL != gets(buff)){ printf("Read line with len: %d\n", strlen(buf

  • Python 批量读取文件中指定字符的实现

    1.背景 从指定的NLP生成的文件中读取指定的字符. 2.待读取文件 是以":"作为分隔符的数据,每一行以回车结束.此文件为XXX.train 3.读取每一句中的汉字 ... file_train = os.path.join(rootDir,"data/train/rg_train_"+modle_date+"_"+aiscene+".train") with open(file_train, 'r')as fp: text

随机推荐