码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】161. One Edit Distance

时间:2018-12-13 21:18:34      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:off   mat   blog   复制   str   html   value   end   note   

Difficulty: Easy

 More:【目录】LeetCode Java实现

Description

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 will only be called once for each test case.

Intuition

题意:int read4(char[] buffer):该函数功能是读取某个文件,每次读取最多4个字符到buffer中,同时返回读取字符个数。要求利用read4()函数来实现read(char[] buf, int n)函数,总共读取n个字符到buf中。

要求很容易实现,每次用read4()来读取字符,用System.arraycopy(src, srcPos, dest, destPos, length)来复制数组即可。关键要注意的是文件的字符数小于n或者大于n的情况。

Solution

	public int read(char[] buf,int n) {
		char[] buffer = new char[4];
		int index=0;
		boolean endOfFile=false;
		while(index<n && !endOfFile) {
			int size=read4(buffer);
			if(size<4)
				endOfFile=true;
			int bytes=Math.min(size, n-index);
			System.arraycopy(buffer, 0, buf, index, bytes);
			index+=bytes;
		}
		return index;
	}

  

Complexity

Time complexity : O(n)

Space complexity :  O(1)

What I‘ve learned

1.

 

 More:【目录】LeetCode Java实现

 

【LeetCode】161. One Edit Distance

标签:off   mat   blog   复制   str   html   value   end   note   

原文地址:https://www.cnblogs.com/yongh/p/10116414.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!