161. One Edit Distance

Description

Given two strings s and t, determine if they are both one edit distance apart.

Note:

There are 3 possiblities to satisify one edit distance apart:

  1. Insert a character into s to get t
  2. Delete a character from s to get t
  3. Replace a character of s to get t

Example 1:

Input: s = "ab", t = "acb"
Output: true
Explanation: We can insert 'c' into s to get t.

Example 2:

Input: s = "cab", t = "ad"
Output: false
Explanation: We cannot get t from s by only one step.

Example 3:

Input: s = "1203", t = "1213"
Output: true
Explanation: We can replace '0' with '1' to get t.

Solution

Two-pointer, time O(n), space O(n)

这道题用DP就显得大材小用了,首先根据sLen和tLen进行剪枝,然后直接Two-pointer即可。

class Solution {
    public boolean isOneEditDistance(String s, String t) {
        if (s == null || t == null) {
            return false;
        }
        
        if (s.length() < t.length()) {
            return isOneEditDistance(t, s);
        }
        
        if (s.length() - t.length() > 1) {
            return false;
        }

        for (int i = 0; i < t.length(); ++i) {
            if (s.charAt(i) == t.charAt(i)) {
                return s.substring(i + 1).equals(t.substring(i))        // replace
                    || s.substring(i + 1).equals(t.substring(i + 1));   // delete
            }
        }
        
        return s.length() - t.length() == 1;
    }
}

或者这样写,也挺清晰的:

class Solution {
    public boolean isOneEditDistance(String s, String t) {
        if (s == null || t == null) {
            return false;
        }
        
        int sl = s.length();
        int tl = t.length();
        
        if (sl < tl) {
            return isOneEditDistance(t, s);
        } else if (sl == tl) {
            return isOneReplace(s, t);
        } else if (sl - tl == 1) {
            return isOneDelete(s, t);
        } else {
            return false;
        }
    }
    
    public boolean isOneReplace(String s, String t) {
        int diff = 0;
        
        for (int i = 0; i < s.length(); ++i) {
            if (s.charAt(i) != t.charAt(i)) {
                ++diff;
            }
        }
        
        return diff == 1;
    }
    
    public boolean isOneDelete(String s, String t) {
        for (int i = 0; i < t.length(); ++i) {
            if (s.charAt(i) != t.charAt(i)) {
                return s.substring(i + 1).equals(t.substring(i));
            }
        }
        
        return true;
    }
}

你可能感兴趣的:(161. One Edit Distance)