Sharing my java code


  • 0
    A
    public class Solution {
    public boolean isOneEditDistance(String s, String t) {
        if(s == null || t == null) return false;
        int slen = s.length();
        int tlen = t.length();
        // if diff is more than one then return false
        if(Math.abs(slen - tlen) > 1) return false;
        
        if(s.length() > t.length()) {
            return isOneEditDistance(t, s);
        }
        
        int x = 0, y = 0;
        
        boolean diffOneChar = false;
        while(x < slen && y < tlen) {
            if(s.charAt(x++) != t.charAt(y++)) {
                diffOneChar = true;
                if(slen != tlen) x--;
                break;
            }
        }
        
        // check whether 's' matched with 't' all the way and diff is 1
        
        if(x == slen && tlen - x == 1) return true;
        
        while(x < slen && y < tlen) {
            if(s.charAt(x++) != t.charAt(y++)) {
                return false;
            }
        }
        
        // length of both s and t are same but it differs with one character
        
        if(diffOneChar && y == tlen &&  x == slen ) return true;
        
        return false;
            
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.