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 called multiple times.

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:

File file("abc");
Solution sol;
// Assume buf is allocated and guaranteed to have enough space for storing all characters from the file.
sol.read(buf, 1); // After calling your read method, buf should contain "a". We read a total of 1 character from the file, so return 1.
sol.read(buf, 2); // Now buf should contain "bc". We read a total of 2 characters from the file, so return 2.
sol.read(buf, 1); // We have reached the end of file, no more characters can be read. So return 0.

Example 2:

File file("abc");
Solution sol;
sol.read(buf, 4); // After calling your read method, buf should contain "abc". We read a total of 3 characters from the file, so return 3.
sol.read(buf, 1); // We have reached the end of file, no more characters can be read. So return 0.

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 may be called multiple times.
  3. Please remember to RESET your class variables declared in Solution, as static/class variables are persisted across multiple test cases. Please see here for more details.
  4. You may assume the destination buffer array, buf, is guaranteed to have enough space for storing n characters.
  5. It is guaranteed that in a given test case the same buffer buf is called by read.

这道题是之前那道 Read N Characters Given Read4 的拓展,那道题说 read 函数只能调用一次,而这道题说 read 函数可以调用多次,那么难度就增加了,为了更简单直观的说明问题,举个简单的例子吧,比如:

buf = "ab", [read(1),read(2)],返回 ["a","b"]

那么第一次调用 read(1) 后,从 buf 中读出一个字符,就是第一个字符a,然后又调用了一个 read(2),想取出两个字符,但是 buf 中只剩一个b了,所以就把取出的结果就是b。再来看一个例子:

buf = "a", [read(0),read(1),read(2)],返回 ["","a",""]

第一次调用 read(0),不取任何字符,返回空,第二次调用 read(1),取一个字符,buf 中只有一个字符,取出为a,然后再调用 read(2),想取出两个字符,但是 buf 中没有字符了,所以取出为空。

但是这道题我不太懂的地方是明明函数返回的是 int 类型啊,为啥 OJ 的 output 都是 vector<char> 类的,然后我就在网上找了下面两种能通过OJ的解法,大概看了看,也是看的个一知半解,貌似是用两个变量 readPos 和 writePos 来记录读取和写的位置,i从0到n开始循环,如果此时读和写的位置相同,那么调用 read4 函数,将结果赋给 writePos,把 readPos 置零,如果 writePos 为零的话,说明 buf 中没有东西了,返回当前的坐标i。然后用内置的 buff 变量的 readPos 位置覆盖输入字符串 buf 的i位置,如果完成遍历,返回n,参见代码如下:

解法一:

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

class Solution {
public:
    int read(char *buf, int n) {
        for (int i = 0; i < n; ++i) {
            if (readPos == writePos) {
                writePos = read4(buff);
                readPos = 0;
                if (writePos == 0) return i;
            }
            buf[i] = buff[readPos++];
        }
        return n;
    }
private:
    int readPos = 0, writePos = 0;
    char buff[4];
};

下面这种方法和上面的方法基本相同,稍稍改变了些解法,使得看起来更加简洁一些:

解法二:

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

class Solution {
public:
    int read(char *buf, int n) {
        int i = 0;
        while (i < n && (readPos < writePos || (readPos = 0) < (writePos = read4(buff))))
            buf[i++] = buff[readPos++];
        return i;
    }
    char buff[4];
    int readPos = 0, writePos = 0;
};

Github 同步地址:

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

类似题目:

Read N Characters Given Read4

参考资料:

https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/

https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/discuss/49598/A-simple-Java-code

https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/discuss/49607/The-missing-clarification-you-wish-the-question-provided

到此这篇关于C++实现LeetCode(158.用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(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

  • 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(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(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(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(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

  • PHP实现读取Excel文件的记录(二)

    <PHP实现读取Excel文件的记录(一)> 中有在PHP中读取Excel的例子,有些麻烦,因为必须要加载很多的文件. 应该有ODBC的读取方法,还没有试,今天的方法简单了很多,只需要加载两个文件即可,这两个文件(OLERead.php.reader.php)我找了好长时间才找到,放在后面. 试验成功的代码: <?php require_once 'reader.php';//加载Reader $excelData = new Spreadsheet_Excel_Reader();//创

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

    复制代码 代码如下: @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与jquery设置和读取cookies

    HTTP协议是一种无状态协议,这意味着你对网站的每一个请求都是独立的,而且因此无法通过它自身保存数据.但这种简单性也是它在互联网早期就广泛传播的原因之一. 不过,它仍然有一种方法能让你用cookies的形式来保存请求之间的信息.这种方法使你能够更有效率的进行会话管理和维持数据. 有两种处理cookies的方式-服务端(php,asp等)和客户端(javascript).在这个教程中,我们将学习到以php和javascript这两种方式如何去创建cookies. Cookies and php s

  • jsp文件操作之读取篇

    文件操作是网站编程的重要内容之一,asp关于文件操作讨论的已经很多了,让我们来看看jsp中是如何实现的. 这里用到了两个文件,一个jsp文件一个javabean文件,通过jsp中调用javabean可以轻松读取文本文件,注意请放置一个文本文件afile.txt到web根目录的test目录下,javabean文件编译后将class文件放到对应的class目录下(tomcat环境). Read.jsp <html> <head> <title>读取一个文件</titl

  • android文件操作——读取assets和raw文件下的内容

    来自Resources和Assets 中的文件只可以读取而不能进行写的操作. assets文件夹里面的文件都是保持原始的文件格式,需要用AssetManager以字节流的形式读取文件. 1. 先在Activity里面调用getAssets() 来获取AssetManager引用. 2. 再用AssetManager的open(String fileName, int accessMode) 方法则指定读取的文件以及访问模式就能得到输入流InputStream. 3. 然后就是用已经open fi

  • 基于JS如何实现给字符加千分符(65,541,694,158)

    本文以65,541,694,158为例,介绍实现给字符加千分符的方法,代码比较简单易懂,具体代码如下所示: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>给字符加千分号</title> <script type="text/javascript"> var str = '2359844564654'; func

随机推荐