博文中会简要介绍Leetcode P0157题目分析及解题思路。
“Read N Characters Given Read4”这道题比较简单,主要考察细心和耐心程度。对于一个给定的字符串(文件),读取其n
个字符有多种情况,比如给定字符串的字符树不足n
个,调用read4
时剩余字符不足4个等等。
Given a file and assume that you can only read the file using a given method read4, implement a method to read n characters.
以下是Java的题解代码实现。
/**
* The read4 API is defined in the parent class Reader4.
* int read4(char[] buf4);
*/
public class Solution extends Reader4 {
/**
* @param buf Destination buffer
* @param n Number of characters to read
* @return The number of actual characters read
*/
public int read(char[] buf, int n) {
int remained = n, count = -1, itr = 0, len = 0;
char[] buf4 = new char[4];
while (remained >= 4) {
count = super.read4(buf4);
// No enough characters
if (count == 0)
return len;
// Copy
len += count;
for (int idx=0; idx<count; ++idx)
buf[itr*4+idx] = buf4[idx];
++itr;
remained -= count;
}
// Min of actual remained and required remained
count = Math.min(super.read4(buf4), remained);
for (int idx=0; idx<count; ++idx)
buf[itr*4+idx] = buf4[idx];
len += count;
return len;
}
}
以下是C++的题解代码实现。
/**
* 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 remained = n, count = -1, itr = 0, len = 0;
char* buf4 = new char[4];
while (remained >= 4) {
count = read4(buf4);
// No enough characters
if (count == 0)
return len;
// Copy
len += count;
for (int idx=0; idx<count; ++idx)
buf[itr*4+idx] = buf4[idx];
++itr;
remained -= count;
}
// Min of actual remained and required remained
count = min(read4(buf4), remained);
for (int idx=0; idx<count; ++idx)
buf[itr*4+idx] = buf4[idx];
len += count;
return len;
}
};