161. One Edit Distance
题目的原意: 写一个函数判断两个给定的String是否是编辑距离为一。
给定条件:两个字符串。
解题思路:用one edit的算法会超时,可以利用只有一个编辑的距离的特点。将问题细分为出现一个距离的一下几种情况。
1. 两个字符串长度一样的时候,说明只有一个字符串不一样,所以只需要看对应位置的连个字符是否一致,是否只有一个字符不一致就可以了。
2. 两个字符串长度相差一个。这个时候,在长的字符串中跳过一个字符就可以对应所有其他的字符。或者其他所有的字符都相符,留下最后一个字符在长的字符串中,说明两个字符串为编辑距离为一。
3. 两个字符串长度相差大于一,可以返回false。
public boolean isOneEditDistance(String s, String t) {
int m = s.length();
int n = t.length();
int shift = n - m;
//if m > n, we switch two string.
if (m > n) {
return isOneEditDistance(t, s);
}
//shift > 1, more than one edit distance, should return false
if (shift > 1) return false;
//consider while loop to increment i when the character at index i for both s and t
//are the same
int i = 0;
while (i < m && s.charAt(i) == t.charAt(i)) {
i++;
}
//when i == m, there are two cases, one is shift == 0 which return false,
//one is shift > 0 which return true;
if (i == m) {
return shift > 0;
}
//if i doesn't equal to m, because shift only is 0 or 1, we could increment index
//when shift equals 0. otherwise(shift is not 0 && i is not m), we could skip index
//in longer String by incrementing shift value.
if (shift == 0) i++;
while (i < m && s.charAt(i) == t.charAt(i + shift)) {
i++;
}
//now if the index i equals to m, then we could return true, otherwise return false.
return i == m;
}