LeetCode 157. Read N Characters Given Read4
157. Read N Characters Given Read4
Difficulty: Easy
Given a file and assume that you can only read the file using a given method read4, implement a method to read n characters.
Method read4:
The API read4 reads 4 consecutive characters from the file, then writes those characters into the buffer array buf.
The return value is the number of actual characters read.
Note that read4() has its own file pointer, much like FILE *fp in C.
Definition of read4:
1 | Parameter: char[] buf |
Below is a high level example of how read4 works:
1 | File file("abcdefghijk"); // File is "abcdefghijk", initially file pointer (fp) points to 'a' |
Method read:
By using the read4 method, implement the method read that reads n characters from the file and store it in the buffer array buf. Consider that you cannot manipulate the file directly.
The return value is the number of actual characters read.
Definition of read:
1 | Parameters: char[] buf, int n |
Example 1:
1 | Input: file = "abc", n = 4 |
Example 2:
1 | Input: file = "abcde", n = 5 |
Example 3:
1 | Input: file = "abcdABCD1234", n = 12 |
Example 4:
1 | Input: file = "leetcode", n = 5 |
Note:
- Consider that you cannot manipulate the file directly, the file is only accesible for
read4but not forread. - The
readfunction will only be called once for each test case. - You may assume the destination buffer array,
buf, is guaranteed to have enough space for storing n characters.
Solution
Language: Java
1 | /** |