Leetcode-Read N Characters Given Read4 II
2024-08-31 00:49:16
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.
Analysis:
Since the function can be called multiple times, we need to record the left over content in the buffer of read4, and put them in some place. For the next call, we need to read content from the carry over buffer first.
Solution:
/* The read4 API is defined in the parent class Reader4.
int read4(char[] buf); */ public class Solution extends Reader4 {
/**
* @param buf Destination buffer
* @param n Maximum number of characters to read
* @return The number of characters read
*/ public char[] carry;
public int index; public int read(char[] buf, int n) {
int left = n; //Put carry over into buf, and destroy the carry over array!
if (carry!=null){
while (left>0 && index<carry.length){
buf[n-left]=carry[index];
left--;
index++;
}
if (index>=carry.length){
carry=null;
index=-1;
}
} char[] tempBuf = new char[4];
while (left>0){
int num = read4(tempBuf);
//if the read number is larger then what we need, then we just put the left number of chars into buf.
//And put the rest chars into carry array.
if (num>left){
carry = new char[num-left];
for (int i=left;i<num;i++)
carry[i-left] = tempBuf[i];
index = 0;
} int end = Math.min(num,left);
for (int i=0;i<end;i++){
buf[n-left] = tempBuf[i];
left--;
} //If reach EOF.
if (left>0 && num<4) break;
} return n-left; }
}
最新文章
- SqlServer 注入技巧
- OpenCV学习笔记——点击显示鼠标坐标
- 获取真实ip的报告
- MSP430F149学习之路——UART
- HelloWorld IL代码
- XSS 前端防火墙(2):可疑模块拦截
- u盘启动盘制作工具
- Linux学习之rcp命令
- Hadoop 相关问题
- CSS空白符处理!
- centos6.7系统安装流程
- form 表单提交返回值问题
- Latex 经常见到的问题和解决方法
- drf框架之 路飞学城(第二天)
- Nginx详解二十九:基于Nginx的中间件架构设计
- OC的反射机制
- Fedora 19安装mysql
- 定时任务redis锁+自定义lambda优化提取冗余代码
- 安装Nginx并为node.js设置反向代理
- Python中第三方库的安装