最近我遇到了这个问题:
Given two strings, return true if they are one edit away from each other,else return false.
An edit is insert/replace/delete a character.
Ex. {"abc","ab"}->true, {"abc","adc"}->true, {"abc","cab"}->false
解决这个问题的一种方法是使用动态规划找到两个字符串之间的编辑距离,并检查它是否为1。这将需要O(N2)时间。有没有一种线性时间的方法,因为我们只需要检查它们是否相差1次编辑?
我下面写的代码适用于大多数情况,但在 {"m",""} 这样的案例中会失败。
public boolean isOneEditDistance(String s1,String s2){
if(s1==null || s2==null)
return true;
if(s1.equals(s2))
return false;
if (Math.abs(s1.length() - s2.length()) > 1)
return false;
int i = -1;
int j = -1;
while (true)
{
i++;
j++;
if (i == s1.length())
return true;
if (s1.charAt(i) == s2.charAt(j))
continue;
if (i != j)
return false;
if (s1.length() < s2.length())
i--;
else
j--;
}
}