LeetCode 161. One Edit Distance(编辑距离)

15 篇文章 0 订阅
12 篇文章 0 订阅

原题网址:https://leetcode.com/problems/one-edit-distance/

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

方法:两个字符串长度最多相差1,或者最多只有一个字符不同。

public class Solution {
    public boolean isOneEditDistance(String s, String t) {
        if (s == null && t == null) return false;
        if (s == null) return t.length() == 1;
        if (t == null) return s.length() == 1;
        if (s.length() < t.length()) {
            String temp = s;
            s = t;
            t = temp;
        }
        if (s.length() == 1 && t.length() == 0) return true;
        if (s.length() > t.length() + 1) return false;
        if (s.length() == t.length()) {
            int dist = 0;
            for(int i=0; i<s.length(); i++) {
                if (s.charAt(i) != t.charAt(i)) {
                    dist ++;
                    if (dist > 1) return false;
                }
            }
            return dist == 1;
        } else {
            int dist = 0;
            for(int i=0; i<t.length(); i++) {
                if (t.charAt(i) == s.charAt(i+dist)) continue;
                dist ++;
                if (dist > 1) return false;
                if (t.charAt(i) == s.charAt(i+dist)) continue;
                return false;
            }
            return dist <= 1;
        }
    }
}

另一种实现(不如上一种简洁):

public class Solution {
    public boolean isOneEditDistance(String s, String t) {
        char[] sa = s.toCharArray();
        char[] ta = t.toCharArray();
        if (Math.abs(sa.length-ta.length) > 1) return false;
        if (sa.length < ta.length) {
            char[] temp = sa;
            sa = ta;
            ta = temp;
        }
        int i=0, j=0;
        int dist = 0;
        while (i<sa.length || j <ta.length) {
            if (i==sa.length) { dist++; j++; }
            else if (j==ta.length) { dist++; i++; }
            else if (sa[i]==ta[j]) { i++; j++; }
            else {
                if (i<sa.length-1 && sa[i+1] == ta[j]) {
                    i ++;
                } else {
                    i ++;
                    j ++;
                }
                dist ++;
            }
            if (dist>1) return false;
        }
        return dist == 1;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值