1. 程式人生 > >【LeetCode】161. One Edit Distance

【LeetCode】161. One Edit Distance

Difficulty: Medium

 More:【目錄】LeetCode Java實現

Description

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

Intuition

同時遍歷比較S和T的字元,直至遇到不同的字元:如果S和T的字元個數相同時,跳過不同的那個字元,繼續遍歷;如果S和T的字元個數相差為1時,跳過較長的字串的當天字元,繼續遍歷。如果剩下的字元都相等,那麼返回true,其餘情況為false。

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)

Space complexity :  O(1)

What I've learned

1. 程式碼第5行,學會交換,僅需要實現S字串的長度大於T字串的情況。

 

 More:【目錄】LeetCode Java實現