https://leetcode.com/problems/one-edit-distance/
Given two strings S and T, determine if they are both one edit distance apart.
One Edit Distance即是:
1. 插入一个字符
2. 更改一个字符, 如ab->ac
所以分情况是:
1. 如果两个字符串等长,那么其中有一个字符不相同就可以
2. 如果两个字符串长度相差1,那么除了被插入的字符,其余字符相同
3. 如果两个字符串长度相差大于1,那么肯定不只1个edit distance了
public class Solution {
public boolean isOneEditDistance(String s, String t) {
int m = s.length();
int n = t.length();
if(m>n) return isOneEditDistance(t, s);
int shift = n-m;
if(shift>1) return false;
if(shift==0){
int i = 0;
while(i<m && s.charAt(i)==t.charAt(i)) i++;
if(i==m) return false;
i++;
while(i<m && s.charAt(i) == t.charAt(i)) i++;
return i==m;
}
else{
int i = 0;
while(i<m && s.charAt(i)==t.charAt(i)) i++;
if(i==m) return true;
while(i<m && s.charAt(i)==t.charAt(i+shift)) i++;
return i==m;
}
}
}
public class Solution {
public boolean isOneEditDistance(String s, String t) {
int m = s.length();
int n = t.length();
if(m>n) return isOneEditDistance(t, s);
int shift = n-m;
if(shift>1) return false;
int i = 0;
while(i<m && s.charAt(i)==t.charAt(i)) i++;
if(i==m) return shift>0;
if(shift==0) i++;
while(i<m && s.charAt(i)==t.charAt(i+shift)) i++;
return i==m;
}
}
合并两种情况!