Leetcode-Read N Characters Given Read4 II
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Leetcode-Read N Characters Given Read4 II,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1899字,纯文字阅读大概需要3分钟。
内容图文
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:
1 /* The read4 API is defined in the parent class Reader4. 2 int read4(char[] buf); */ 3 4 public class Solution extends Reader4 { 5/** 6 * @param buf Destination buffer 7 * @param n Maximum number of characters to read 8 * @return The number of characters read 9*/1011publicchar[] carry; 12publicint index; 1314publicint read(char[] buf, int n) { 15int left = n; 1617//Put carry over into buf, and destroy the carry over array!18if (carry!=null){ 19while (left>0 && index<carry.length){ 20 buf[n-left]=carry[index]; 21 left--; 22 index++; 23 } 24if (index>=carry.length){ 25 carry=null; 26 index=-1; 27 } 28 } 2930char[] tempBuf = newchar[4]; 31while (left>0){ 32int num = read4(tempBuf); 33//if the read number is larger then what we need, then we just put the left number of chars into buf. 34//And put the rest chars into carry array.35if (num>left){ 36 carry = newchar[num-left]; 37for (int i=left;i<num;i++) 38 carry[i-left] = tempBuf[i]; 39 index = 0; 40 } 4142int end = Math.min(num,left); 43for (int i=0;i<end;i++){ 44 buf[n-left] = tempBuf[i]; 45 left--; 46 } 4748//If reach EOF.49if (left>0 && num<4) break; 50 } 5152return n-left; 5354 } 55 }
原文:http://www.cnblogs.com/lishiblog/p/4160863.html
内容总结
以上是互联网集市为您收集整理的Leetcode-Read N Characters Given Read4 II全部内容,希望文章能够帮你解决Leetcode-Read N Characters Given Read4 II所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。