my logical solution


  • 0
    L
    //one time coding solution, ugly but logical
    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 length is not equal, do a validation when length difference is 1.
            if(slen != tlen){
                if(Math.abs(slen - tlen) == 1){
                    if(slen < tlen){
                        return util(s,t);
                    }else{
                        return util(t,s);
                    }
                }else{
                    return false;
                }
            }
            //if length is equal, then it's a straight forward check.
            int count = 0;
            for(int i = 0;i<slen;i++){
                if(s.charAt(i) != t.charAt(i)) count++;
                if(count > 1) return false;
            }
            if(count == 1) return true;
            
            return false;
        }
        
        private boolean util(String s, String t){
            int ps = 0;
            int pt = 0;
            int count = 0;
            while(ps < s.length()){
                if(s.charAt(ps) != t.charAt(pt)){
                    count++;
                }else{
                    ps++;
                }
                pt++;
                if(count > 1) return false;
            }
            return true;
        }
    

    }


Log in to reply
 

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