原题网址:https://leetcode.com/problems/one-edit-distance/
Given two strings S and T, determine if they are both one edit distance apart.
方法:两个字符串长度最多相差1,或者最多只有一个字符不同。
public class Solution {
public boolean isOneEditDistance(String s, String t) {
if (s == null && t == null) return false;
if (s == null) return t.length() == 1;
if (t == null) return s.length() == 1;
if (s.length() < t.length()) {
String temp = s;
s = t;
t = temp;
}
if (s.length() == 1 && t.length() == 0) return true;
if (s.length() > t.length() + 1) return false;
if (s.length() == t.length()) {
int dist = 0;
for(int i=0; i<s.length(); i++) {
if (s.charAt(i) != t.charAt(i)) {
dist ++;
if (dist > 1) return false;
}
}
return dist == 1;
} else {
int dist = 0;
for(int i=0; i<t.length(); i++) {
if (t.charAt(i) == s.charAt(i+dist)) continue;
dist ++;
if (dist > 1) return false;
if (t.charAt(i) == s.charAt(i+dist)) continue;
return false;
}
return dist <= 1;
}
}
}
另一种实现(不如上一种简洁):
public class Solution {
public boolean isOneEditDistance(String s, String t) {
char[] sa = s.toCharArray();
char[] ta = t.toCharArray();
if (Math.abs(sa.length-ta.length) > 1) return false;
if (sa.length < ta.length) {
char[] temp = sa;
sa = ta;
ta = temp;
}
int i=0, j=0;
int dist = 0;
while (i<sa.length || j <ta.length) {
if (i==sa.length) { dist++; j++; }
else if (j==ta.length) { dist++; i++; }
else if (sa[i]==ta[j]) { i++; j++; }
else {
if (i<sa.length-1 && sa[i+1] == ta[j]) {
i ++;
} else {
i ++;
j ++;
}
dist ++;
}
if (dist>1) return false;
}
return dist == 1;
}
}