Saturday, November 28, 2015

[leetcode]One Edit Distance

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Solution {
    public boolean isOneEditDistance(String s, String t) {
        if (s == null) return t == null;
        if (t == null) return s == null;
        if (s.equals(t)) return false;
        if (Math.abs(s.length()-t.length())>1) return false;
        if (s.length() < t.length()) return isOneEditDistance(t, s);
        boolean findDiff = false;
        for (int i = 0; i < s.length()-1&&!findDiff; i++){
            if (s.charAt(i) != t.charAt(i)){
               findDiff = true;
               if (s.length() == t.length()){
                   t = t.substring(0,i)+s.charAt(i)+t.substring(i+1, t.length());
               }else{
                   t = t.substring(0,i)+s.charAt(i)+t.substring(i, t.length());
               }
            }
        }
        if (findDiff) return s.equals(t);
        return s.substring(0, s.length()-1).equals(t.substring(0, s.length()-1));
    }
}

No comments:

Post a Comment