One Edit Distance

161. One Edit Distance

题目的原意: 写一个函数判断两个给定的String是否是编辑距离为一。

给定条件:两个字符串。

解题思路:用one edit的算法会超时,可以利用只有一个编辑的距离的特点。将问题细分为出现一个距离的一下几种情况。

              1. 两个字符串长度一样的时候,说明只有一个字符串不一样,所以只需要看对应位置的连个字符是否一致,是否只有一个字符不一致就可以了。

              2. 两个字符串长度相差一个。这个时候,在长的字符串中跳过一个字符就可以对应所有其他的字符。或者其他所有的字符都相符,留下最后一个字符在长的字符串中,说明两个字符串为编辑距离为一。

               3. 两个字符串长度相差大于一,可以返回false。

public boolean isOneEditDistance(String s, String t) {
    int m = s.length();
    int n = t.length();
    int shift = n - m;

    //if m > n, we switch two string.
    if (m > n) {
        return isOneEditDistance(t, s);
    }
    //shift > 1, more than one edit distance, should return false
    if (shift > 1) return false;
    //consider while loop to increment i when the character at index i for both s and t
    //are the same
    int i = 0;
    
    while (i < m && s.charAt(i) == t.charAt(i)) {
        i++;
    }
    
    //when i == m, there are two cases, one is shift == 0 which return false,
    //one is shift > 0 which return true;
    if (i == m) {
        return shift > 0;
    }

    //if i doesn't equal to m, because shift only is 0 or 1, we could increment index
    //when shift equals 0. otherwise(shift is not 0 && i is not m), we could skip index
    //in longer String by incrementing shift value.
    if (shift == 0) i++;
    while (i < m && s.charAt(i) == t.charAt(i + shift)) {
        i++;
    }
    //now if the index i equals to m, then we could return true, otherwise return false.
    return i == m;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值