// Forward declaration of the read4 API.
int read4(char *buf);
const int size = 4;
class Solution {
private:
char buffer[size+1];
int cnt;
int offset;
int readFromBuffer(char *buf, int n){
int amount;
for(amount=0;cnt<n && buffer[offset];buf[cnt++]=buffer[offset++],amount++);
return amount;
}
public:
/**
* @param buf Destination buffer
* @param n Maximum number of characters to read
* @return The number of characters read
*/
Solution(){
memset(buffer,0,sizeof(char)*(size+1));
offset = 0;
}
int read(char *buf, int n) {
cnt = 0;
readFromBuffer(buf,n);
for(int amount = size;
n>cnt && amount==size;
buffer[read4(buffer)]='\0', offset = 0, amount = readFromBuffer(buf,n));
buf[cnt]='\0';
return cnt;
}
};
Leetcode Read N Characters Given Read4 (I,II同一款程序)
最新推荐文章于 2021-08-05 13:53:38 发布