Read N Characters Given Read4
题目地址:
https://leetcode.com/problems/read-n-characters-given-read4/description/
题目:
这道题就是用他给的api来做,每次尝试读取4个char放到temp里,然后做循环将temp里的char转移到globle的buf里。
代码:
Follow up:
https://leetcode.com/problems/read-n-characters-given-read4/description/
题目:
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.这道题就是用他给的api来做,每次尝试读取4个char放到temp里,然后做循环将temp里的char转移到globle的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 int read(char[] buf, int n) {
int p = 0;
while(p < n){
char[] temp = new char[4];
int k = read4(temp);
for(int i = 0; i < k && p < n; i++){
buf[p] = temp[i];
p++;
}
if(k < 4){
return p;
}
}
return p;
}
}
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.
解题思路:
Think that you have 4 chars "a, b, c, d" in the file, and you want to call your function twice like this:
- read(buf, 1); // should return 'a'
- read(buf, 3); // should return 'b, c, d'
All the 4 chars will be consumed in the first call. So the tricky part of this question is how can you preserve the remaining 'b, c, d' to the second call.
p-> the pointer to the destination buffer
bufPointer -> the pointer to the temporary buf
k -> the real length for each read4 API
代码:
public class Solution extends Reader4 {
/**
* @param buf Destination buffer
* @param n Maximum number of characters to read
* @return The number of characters read
*/
private int buffPtr = 0;
private int k = 0;
char[] temp = new char[4];
public int read(char[] buf, int n) {
int p = 0;
while(p < n){
if(buffPtr == 0){
k = read4(temp);
}
if(k == 0){
break;
}
while(p < n && buffPtr < k){
buf[p++] = temp[buffPtr++];
}
if(buffPtr >= k){
buffPtr = 0;
}
}
return p;
}
}

Comments
Post a Comment