161. One Edit Distance

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

public class Solution {
    public boolean isOneEditDistance(String s, String t) {
        if(Math.abs(s.length() - t.length()) > 1) return false;

        if(s.length() == t.length()){
            int count =0;
            int i = 0;
            while(i < s.length()){
                if(s.charAt(i) != t.charAt(i)) count++;
                if(count > 1) break;
                i++;
            }
            return count == 1;
        }else{
            return s.length() > t.length() ? isOneDelete(s, t) : isOneDelete(t,s);
        }
    }

    private boolean isOneDelete(String longer, String shorter){
        int i=0;
        for(; i< shorter.length(); i++){
            if(longer.charAt(i) != shorter.charAt(i))break;
        }

        if(i == shorter.length()) return true;
        return shorter.substring(i, shorter.length()).equals(longer.substring(i+1, longer.length()));
    }
}
public class Solution {
    public boolean isOneEditDistance(String s, String t) {
        int sl = s.length();
        int tl = t.length();
        int delta = Math.abs(sl-tl);

        if(delta > 1) return false;
        else if( delta == 0){
            int i = 0;
            while( i < s.length() && s.charAt(i) == t.charAt(i)){
                i++;
            }
            if(i == sl) return false;
            else return s.substring(i+1).equals(t.substring(i+1));
        }else{
            return sl > tl ? isOneDelete(s, t) : isOneDelete(t, s);
        }
    }

    boolean isOneDelete(String l, String s){
        int i=0;
        for(; i< s.length(); i++){
            if(l.charAt(i) != s.charAt(i)) break;
        }

        if(i == s.length()) return true;

        return s.substring(i).equals(l.substring(i+1));
    }
}

results matching ""

    No results matching ""