Description
Given two strings S and T, determine if they are both one edit distance apart.
Example
Given s ="aDb"
, t ="adb"
returntrue
Solution
依据两个字符串的长度讨论:
如果m和n之间的差距大于1,返回false
小trick,只讨论m<n的情况,对于m>n的情况,交换两个字符串的位置
m!=n时,从头遍历两个字符串,t中第一个和s中对应位置不同的字符,一定是被delete的那个
m=n时,遍历两个字符串数不相同的字符的个数即可
public class Solution {
/*
* @param s: a string
* @param t: a string
* @return: true if they are both one edit distance apart or false
*/
public boolean isOneEditDistance(String s, String t) {
// write your code here
int m = s.length();
int n = t.length();
if (m != n) {
if (Math.abs(m - n) > 1) {
return false;
}
if (m > n) {
return isOneEditDistance(t, s);
}
for (int i = 0; i < m; i++) {
if (s.charAt(i) != t.charAt(i)) {
return s.substring(i).equals(t.substring(i + 1));
}
}
return true;
} else {
int count = 0;
for (int i = 0; i < m; i++) {
if (s.charAt(i) != t.charAt(i)) {
count++;
}
}
return count == 1;
}
}
}