161. One Edit Distance

class Solution {
    public boolean isOneEditDistance(String s, String t) {
      int min = Math.min(s.length(), t.length());
      for(int i = 0; i < min; i++){
        if(s.charAt(i) != t.charAt(i)){
          if(s.length() == t.length()){
            return s.substring(i+1).equals(t.substring(i+1));
          }else{
            if(s.length() > t.length()){
              return s.substring(i+1).equals(t.substring(i));
            }else{
              return t.substring(i+1).equals(s.substring(i));
            }
          }
        }
      }
      return Math.abs(s.length() - t.length()) == 1;
    }
}

 

class Solution {
    public boolean isOneEditDistance(String s, String t) {
      if(Math.abs(s.length() - t.length()) > 1){
        return false;
      }
      
      int len = Math.min(s.length(), t.length());
      
      for(int i = 0; i < len; i++){
        if(s.charAt(i) != t.charAt(i)){
          if(s.length() == t.length()){
            return match(s, t, i+1, i+1);
          }else if (s.length() > t.length()){
            return match(s, t, i+1, i);
          }else{
            return match(s, t, i, i+1);
          }
        }
      }
      return Math.abs(s.length() - t.length()) == 1;
    }
  
  
    private boolean match(String s, String t, Integer sindex, Integer tindex){
      
      for(int i = 0; i < s.length() - sindex; i++){
        if(s.charAt(sindex++) == t.charAt(tindex++)){
          return false;
        }
      }
      return true;
    }
}





 Wrong Answer 
Input:
"ab"
"acb"
Output:
false
Expected:
true

 

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.

posted on 2018-07-18 13:16  猪猪&#128055;  阅读(85)  评论(0)    收藏  举报

导航