g****v 发帖数: 971 | 1 Read N Characters Given Read4 II - Call multiple times
测试的输出是:
Input: "ab", [read(0),read(1),read(2),read(1)]
Output: ["","a","b","b"]
Expected: ["","a","b",""]
我的思路很简单,就是把上次没读完的保留下来(并且是把没读完的字符移动到index
0). 下次读的时候先读上次剩下的。但不知道为什么不对?
class Solution {
int left = 0; //length of left chars of last time reading, staring from
0 of leftover.
char leftover[4];//left chars are stored here.
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) {
if(n==0) return 0;
//if leftover has more chars than that of to-read
if(n <= left)
{
memcpy(buf, leftover, n);
left = left - n;
for(int i=0;i
leftover[i] = leftover[i+n];
return n;
}
int result = 0;
//copy leftover first if they exist.
if(left != 0)
{
memcpy(buf, leftover, left);
result += left;
}
//now we need read n-left chars to buf+left
int count = 0;
int newn = n - left;
while(result < newn)
{
count = read4(leftover);
if(count == 0 )
{
left = 0;
break;
}
if(result + count <= newn)
{
memcpy(buf+left+result, leftover, count);
result += count;
if(count < 4)
{
for(int i=0;i
leftover[i] = leftover[i+count];
left = newn-count;
break;
}
}
else
{
memcpy(buf+left+result, leftover, newn-result);
for(int i=0;i
leftover[i] = leftover[i+newn-result];
left = count-(newn-result);
result = n;
}
}
return result;
}
}; | g****v 发帖数: 971 | | g****v 发帖数: 971 | | l*********u 发帖数: 19053 | 4 for(int i=0;i
leftover[i] = leftover[i+n];
return n;// this one?
index
from
【在 g****v 的大作中提到】 : Read N Characters Given Read4 II - Call multiple times : 测试的输出是: : Input: "ab", [read(0),read(1),read(2),read(1)] : Output: ["","a","b","b"] : Expected: ["","a","b",""] : 我的思路很简单,就是把上次没读完的保留下来(并且是把没读完的字符移动到index : 0). 下次读的时候先读上次剩下的。但不知道为什么不对? : class Solution { : int left = 0; //length of left chars of last time reading, staring from : 0 of leftover.
| g****v 发帖数: 971 | 5 谢谢,这个地方不对,但是这个testcase没运行到这段。
改完后还是相同的错误。
【在 l*********u 的大作中提到】 : for(int i=0;i: leftover[i] = leftover[i+n]; : return n;// this one? : : index : from
|
|