An edit between two strings is one of the following changes:
Add a character
Delete a character
Change a character
Given two string s1 and s2, find if s1 can be converted to s2 with exactly one edit. Expected time complexity is O(m+n) where m and n are lengths of two strings.
可以做的操作只有三种,因此s1和s2的长度要不是相等,要不然就是差一个1。且删除添加一个字符可看做是一个操作,因为题目并没有规定谁是原字符串。
最后可简单总结为:
1. 两个字符串的长度之差大于1,则返回false
2. 两个字符串的长度之差等于1,则判断长的字符串是否只有一个字符丢失,且注意一下最后一位丢失的情况。
3. 两个字符串的长度之差等于0,则判断是否只有一个字符不同。
public boolean isOneEditDistance(String s1, String s2){
if(s1 == null || s2 == null) return false;
if(s2.length() > s1.length()) return compare(s2, s1);
return compare(s1, s2);
}
public boolean compare(String s1, String s2){
int count = s1.length() - s2.length();
if(count > 1) return false;
int i = 0;
boolean mark = false;
for(int j = 0; j < s2.length(); ++j){
if(s1.charAt(i++) != s2.charAt(j)){
if(mark) return false;
else{
if (count == 1 && s1.charAt(i++) != s2.charAt(j)) return false;
mark = true;
}
}
}
return mark || (i == s1.length() - 1); //注意如果添加在最后一位的情况
}