problem:
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 are only 3 characters left in the file.
read4
by using the API, implement the function that int read(char *buf, int n)
reads n characters from the file.
Note:
The function is only being read
called once for each test case.
Analysis:
This problem isn't hard , but it's easy-to-be wrong. General Idea:since Read4 (Char[] buf) would always filled buf with four characters, no matter how many characters left in the file. Case: Read4 (Char[] buf) may fill buf with "[' A ', ' B ', x00, x00]",ifThere is only and characters left in the file. Thus we could not directly use"Read4" Over "char[] buf", and we should take advantage of a temp_buffer for ThisPurpose. Thus we could base on thereturn intof "Read 4"To add the character into BUF. There is possible-situation of the end:1. There is not enough characters left in the file. ( forThe target N)2. N was meeted. for Thiscondition, we should maintain a count of copied words.if(Cur_len < 4 | | count = =N) Break; When we copy the characters from the Temp_buffer, we should only copy the valid range.1. The actual words we have read (could less than 4)2. IFF we have already reach the target N. (may just need part of the characters) Read_len=read4 (temp_buffer); Cur_len= Math.min (Read_len, N-count); Then we should copy those characters into BUF. for(inti = 0; i < Cur_len; i++) Buf[count+i] =Temp_buffer[i]; Note:the Cur_len' s computation is very important along the process!!!
Solution:
Public classSolutionextendsReader4 {/** * @parambuf Destination Buffer *@paramn Maximum number of characters to read *@returnThe number of characters read*/ Public intReadChar[] buf,intN) {if(BUF = =NULL) Throw NewIllegalArgumentException ("BUF is null"); if(n <= 0) return0; intCount = 0, Read_len = 0, Cur_len = 0; Char[] Temp_buffer =New Char[4]; while(true) {Read_len=read4 (Temp_buffer); Cur_len= Math.min (Read_len, N-count); for(inti = 0; i < Cur_len; i++) Buf[count+i] =Temp_buffer[i]; Count+=Cur_len; if(Cur_len < 4 | | count = =N) Break; } returncount; }}
[leetcode#157] Read N characters Given Read4