One Edit Distance

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

Tips:

O(n)

对s和t的每一位进行比较。遇到不同时有三种情况:

  1. s和t的长度相同,则可以替换这一位,如果后面的全都一样则返回true;
  2. t比s长,则去掉t的这一位看剩下的是否与s相同;
  3. s比t长,则去掉s的这一位看剩下的是否与相同。
  4. 如果之前的都一样,而两个string长度不同,则判断是不是只多了最后一位。

Code:

public class Solution {
    public boolean isOneEditDistance(String s, String t) {
        for (int i = 0; i < Math.min(s.length(), t.length()); i++) { 
            if (s.charAt(i) != t.charAt(i)) {
                // s has the same length as t, so the only possibility is replacing one char in s and t
                if (s.length() == t.length()) {
                    return s.substring(i + 1).equals(t.substring(i + 1));
                }
                // t is longer than s, so the only possibility is deleting one char from t
                else if (s.length() < t.length()) {
                    return s.substring(i).equals(t.substring(i + 1));
                }
                // s is longer than t, so the only possibility is deleting one char from s
                else {
                    return t.substring(i).equals(s.substring(i + 1));
                }
            }
        }       
        //All previous chars are the same, the only possibility is deleting the end char in the longer one of s and t 
        return Math.abs(s.length() - t.length()) == 1;        
    }
}

results matching ""

    No results matching ""