【LeetCode】158. Read N Characters Given Read4 II - Call multiple times

Difficulty: Hard

 More:【目录】LeetCode Java实现

Description

Similar to Question [Read N Characters Given Read4], but the read function may be called multiple times.

Intuition

题意:本题与上一题的区别就是连续多次调用read()函数,所以需要将存储4个字符的缓存buffer定义为全局变量,此外全局变量还需要定义buffer[]中的开始下标和缓存长度。本题中,需要注意的是,调用完一次read()函数后,可能没办法把buffer全部读完,所以要考虑到下一次调用read()函数时,对buffer的操作。详见代码。

Solution

public class Solution extends Reader4 {
	private char[] buffer = new char[4];
	int offset = 0, bufsize = 0;  //buffer[]中的开始下标和缓存长度

	/**
	* @param buf Destination buffer
	* @param n Maximum number of characters to read
	* @return The number of characters read
	*/
	public int read(char[] buf, int n) {
		int readBytes=0;  //已读的字符个数
		boolean eof=false;
		while(readBytes<n && !eof) {
			if(bufsize==0) {  //buffer[]中没有缓存了
				bufsize=read4(buffer);
				eof=(bufsize<4);  //不能放到外面!
			}
			int bytes=Math.min(bufsize, n-readBytes);
			System.arraycopy(buffer, offset, buf, readBytes, bytes);
			offset=(offset+bytes)%4;
			bufsize-=bytes;
			readBytes+=bytes;
		}
		return readBytes;
	}
}

  

What I've learned

1.

 

 More:【目录】LeetCode Java实现

 

posted @ 2018-12-19 21:50  华仔要长胖  阅读(259)  评论(0编辑  收藏  举报