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;
    }
}

 

转载于:https://www.cnblogs.com/jiajiaxingxing/p/4579686.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值