One Edit Distance

Given two strings S and T, determine if they are both one edit distance apart.

Hint:
1. If | n – m | is greater than 1, we know immediately both are not one-edit distance apart.
2. It might help if you consider these cases separately, m == n and m ≠ n.
3. Assume that m is always ≤ n, which greatly simplifies the conditional statements. If m > n, we could just simply swap S and T.
4. If m == n, it becomes finding if there is exactly one modified operation. If m ≠ n, you do not have to consider the delete operation. Just consider the insert operation in T.

ref from 达达

感觉好聪明的解法,关键还是corner case的严谨性

http://www.danielbit.com/blog/puzzle/leetcode/leetcode-one-edit-distance

[分析]
最笨的方法就是用Edit Distance算法,其实就是自己之前搞的生物信息学里面的Needleman-Wunsch算法。孤陋寡闻了,搜了一下发现Edit Distance算法是DP的经典题。。。

这个题目只要O(1)的空间,O(n)的时间复杂度。假定有一下几种情况
1)修改一个字符(假定两个String等长)
2)插入一个字符(中间或者结尾)

[注意事项]
1)shift变量的作用

 

code也copy自人家

public class Solution {
    public boolean isOneEditDistance(String s, String t) {
        int m = s.length(), n = t.length();
        if (m>n) return isOneEditDistance(t, s);
        if (n-m>1) return false;
        int i =0, shift = n-m;
        while (i<m && s.charAt(i)==t.charAt(i)) ++i;
        if (i==m) return shift > 0; // if two string are the same (shift==0), return false
        if (shift==0) i++; // if n==m skip current char in s (modify operation in s)
        while (i<m && s.charAt(i)==t.charAt(i+shift)) i++; // use shift to skip one char in t
        return i == m;
    }
}

 

posted @ 2015-06-16 04:16  世界到处都是小星星  阅读(224)  评论(0编辑  收藏  举报