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 only once.
1 public class Solution extends Reader4 { 2 char[] buffer = new char[4]; 3 4 public int read(char[] buf, int n) { 5 int index = 0; 6 int startIndex = 0; 7 int bufferSize = read4(buffer);; 8 while (index < n) { 9 if (startIndex < bufferSize) { 10 buf[index++] = buffer[startIndex++]; 11 } else { 12 bufferSize = read4(buffer); 13 startIndex = 0; 14 if (bufferSize == 0) { 15 break; 16 } 17 } 18 19 } 20 return index; 21 } 22 }
Read N Characters Given Read4 II - Call multiple times
Given a file and assume that you can only read the file using a given method read4
, implement a method read
to read n characters. Your method read
may be called multiple times.
Method read4:
The API read4
reads 4 consecutive characters from the file, then writes those characters into the buffer array buf4
.
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:
Parameter: char[] buf4 Returns: int Note: buf4[] is destination not source, the results from read4 will be copied to buf4[]
Below is a high level example of how read4
works:
File file("abcde"); // File is "abcde", initially file pointer (fp) points to 'a'
char[] buf4 = new char[4]; // Create buffer with enough space to store characters
read4(buf4); // read4 returns 4. Now buf4 = "abcd", fp points to 'e'
read4(buf4); // read4 returns 1. Now buf4 = "e", fp points to end of file
read4(buf4); // read4 returns 0. Now buf4 = "", fp points to end of file
分析:
1 public class Solution extends Reader4 { 2 char[] buffer = new char[4]; 3 int bufferSize = 0, prevIndex = 0; 4 5 public int read(char[] buf, int n) { 6 int index = 0; 7 while (index < n) { 8 if (prevIndex < bufferSize) { 9 buf[index++] = buffer[prevIndex++]; 10 } else { 11 bufferSize = read4(buffer); 12 prevIndex = 0; 13 if (bufferSize == 0) { break; } 14 } 15 } 16 return index; 17 } 18 }