Given two strings S and T, determine if they are both one edit distance apart.
分析:one edit distance,要么S,T长度同样, 仅仅有一对不同char,那么仅仅要跳过这对不同的char,应该能匹配完两个String的;
要么S。T长度相差一。其它部分都匹配,则仅仅要跳过长度长的那个String的不匹配字符继续匹配,假设能够匹配完两个String,则返回true
时间复杂度: 仅仅需一遍扫描, O(n)
public class Solution {
public boolean isOneEditDistance(String s, String t) {
// make s to be the shorter String
if(s.length() > t.length()){
return isOneEditDistance(t, s);
}
if(t.length() - s.length() > 1){
return false;
}
int shift = t.length() - s.length();
int i = 0;
while(i < s.length() && s.charAt(i) == t.charAt(i)){
i++;
}
if(shift == 0){
i++;
while(i < s.length() && s.charAt(i) == t.charAt(i)){
i++;
}
return i == s.length();
}else{
if(i == s.length()){
return true;
}else{
while(i < s.length() && s.charAt(i) == t.charAt(i + 1)){
i++;
}
return i == s.length();
}
}
}
}
又观察了一下,事实上shift == 1 的情况下没有必要单独讨论 if(i == s.length())。能够整合到以下的推断中, 改进例如以下
public class Solution {
public boolean isOneEditDistance(String s, String t) {
// make s to be the shorter String
if(s.length() > t.length()){
return isOneEditDistance(t, s);
}
if(t.length() - s.length() > 1){
return false;
}
int shift = t.length() - s.length();
int i = 0;
while(i < s.length() && s.charAt(i) == t.charAt(i)){
i++;
}
if(shift == 0){
i++;
while(i < s.length() && s.charAt(i) == t.charAt(i)){
i++;
}
return i == s.length();
}else{
while(i < s.length() && s.charAt(i) == t.charAt(i + 1)){
i++;
}
return i == s.length();
}
}
}