【LeetCode】161. One Edit Distance

Difficulty: Medium

 More:【目录】LeetCode Java实现html

Description

Given two strings S and T, determine if they are both one edit distance apart.java

Intuition

同时遍历比较S和T的字符,直至遇到不一样的字符:若是S和T的字符个数相同时,跳过不一样的那个字符,继续遍历;若是S和T的字符个数相差为1时,跳过较长的字符串的当天字符,继续遍历。若是剩下的字符都相等,那么返回true,其他状况为false。post

Solution

	public boolean isOneEditDistance(String s, String t) {
		if(s==null || t==null) 
			return false;
		if(s.length()<t.length())
			return isOneEditDistance(t, s);    //学会交换
		int i=0;
		while(i<t.length() && s.charAt(i)==t.charAt(i))  //注意i小于较短字符串的长度
			i++;
		if(s.length()==t.length()) {
			i++;
			while(i<t.length() && s.charAt(i)==t.charAt(i))
				i++;
		}else if(s.length()-t.length()==1){
			while(i<t.length() && s.charAt(i+1)==t.charAt(i))
				i++;
		}else 
			return false;
		return i==t.length();
	}

   

Complexity

Time complexity : O(n)ui

Space complexity :  O(1)htm

What I've learned

1. 代码第5行,学会交换,仅须要实现S字符串的长度大于T字符串的状况。blog

 

 More:【目录】LeetCode Java实现ip

相关文章
相关标签/搜索