[Leetcode] 158. Read N Characters Given Read4 II - Call multiple times 解题报告

题目

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

思路

建议读者将这道题目和Leetcode 157结合起来思考。它和Leetcode 157的不同之处就在于read(char *buf, int n)方法可能被调用多次,这样就产生了一个问题:上一次调用时读到buffer中的内容可能没有被取尽,所以下次调用read方法时,需要优先从上次没有读完的buffer中读取数据。所以,我们需要在类中记录三个类变量:长度为4的缓冲区(buffer),有效长度(last_length)以及起始位置(last_pos)。每次在调用read(char *buf, int n)的时候,我们首先从buffer中读取剩余数据;然后再调用read4这一API从文件中读取数据(这一部分的思路就和Leetcode 157完全一样了)。

代码

// 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 ret = 0;  
        while(last_pos < last_length && n-- > 0) {       // read the left charachters from last time
            buf[ret++] = buffer[last_pos++];  
        }
        while(n > 0) {  
            last_length = read4(buffer);
            if(last_length == 0) {
                return ret;
            }
            last_pos = 0;  
            while(last_pos < last_length && n-- > 0) {   // read the current chacters until read over or the read length reaches n
                buf[ret++] = buffer[last_pos++];  
            }
        }  
        return ret;
    }
private:
    int last_pos = 0, last_length = 0;  
    char buffer[4];
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值