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

原题网址: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 1) return false;
                }
            }
            return dist == 1;
        } else {
            int dist = 0;
            for(int i=0; i 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 (i1) return false;
        }
        return dist == 1;
    }
}


你可能感兴趣的:(比较,分治策略,距离,字符串,编辑距离,分情况)