0%

158. Read N Characters Given Read4 II - Call multiple times

157. Read N Characters Given Read4的区别是前一次read过的剩余字符下次read的时候直接写进buf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* The read4 API is defined in the parent class Reader4.
* int read4(char *buf4);
*/

class Solution {
public:
/**
* @param buf Destination buffer
* @param n Number of characters to read
* @return The number of actual characters read
*/
int read(char *buf, int n) {
int cnt = 0;
while (b != e && cnt < n) {
buf[cnt++] = buf4[b++];
}
if (cnt == n) return cnt;
b = 0; // cnt不等于n,说明b == e,重置b,更新e读新字符
e = read4(buf4);
if (e == 0) return cnt;
return cnt + read(buf + cnt, n - cnt);
}

char buf4[4];
int b = 0, e = 0;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Forward declaration of the read4 API.
int read4(char *buf);

class Solution {
public:
/**
* @param buf Destination buffer
* @param n Number of characters to read
* @return The number of actual characters read
*/
int read(char *buf, int n) {
int cnt = 0;
while (i < e && cnt < n) { // 在全局buffer的边界之内尽可能多的读字符
buf[cnt++] = t[i++];
}
if (i == e) i = e = 0; // 如果全局buffer里到边界的所有字符都被读走,则重置下标和边界
if (cnt == n) return cnt; // 如果已经读够了需要的字符,则返回
e = read4(t);
if (e == 0) return cnt; // 如果还需要继续读字符但是读出的字符数为0
return cnt + read(buf + cnt, n - cnt); // 如果还需要继续读字符,递归
}

int i = 0, e = 0; // 维护全局buffer的下标和右边界(不一定为4)
char t[4];
};