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.
Note:
The read
function may be called multiple times.
Example 1:
Given buf = "abc" read("abc", 1) // returns "a" read("abc", 2); // returns "bc" read("abc", 1); // returns ""
Example 2:
Given buf = "abc" read("abc", 4) // returns "abc" read("abc", 1); // returns ""
reference:
https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/discuss/49598/A-simple-Java-code
https://segmentfault.com/a/1190000003794420
因为可以调用多次,每一次调用的时候都需要检查上一次是否有未读完的字符串,从上一次未读完的接着读。
e.g.
Given buf = "abc" tmp = {0,0,0,0}, count = 0, ptr = 0
read("abc", 1); // returns "a"
-> index = 0, n = 1, count = read4(tmp) = 4, buf[0]=tmp[0] -> index = 1, ptr = 1, return index = 1
read("abc", 2); // returns "bc"
-> index = 0, n = 2, count = read4(tmp) = 4, buf[0]=tmp[1],buf[1]=tmp[2] -> index = 2, ptr = 3, return index = 2
read("abc", 1); // returns ""
-> index = 0, n = 1, count = read4(tmp) = 4, buf[0]=tmp[3] -> index = 1, ptr = 4 -> ptr = 0, return index = 1
time: O(N), space: O(1)
/* The read4 API is defined in the parent class Reader4. int read4(char[] buf); */ public class Solution extends Reader4 { /** * @param buf Destination buffer * @param n Maximum number of characters to read * @return The number of characters read */ private char[] tmp = new char[4]; private int count = 0; private int ptr = 0; public int read(char[] buf, int n) { int index = 0; while(index < n) { if(ptr == 0) { count = read4(tmp); } if(count == 0) break; while(index < n && ptr < count) { buf[index++] = tmp[ptr++]; } if(ptr == count) ptr = 0; } return index; } }