My Java solution with three cases


  • 2
    L
    //Basic idea:
    
    //Case 1: |s.length - t.length| >=2 : return false;
    //Case 2: |s.length - t.length| == 1: there should be exactly one insertion
    //Case 3: |s.length - t.length| == 0: there should be exactly one replacement
    
     
    
    
            public boolean isOneEditDistance(String s, String t) {
                int x = Math.abs(s.length()-t.length());
                
                if(x>=2){
                    return false;
                }
                
                if(x==1){
                    return compare1(s, t);
                }
                
                return compare0(s, t);
            }
            
            public boolean compare0(String s, String t){
                boolean replaceFound = false;
                int i = 0; //s.length();
                int j = 0; //t.length();
                while(i<s.length()){
                    if(s.charAt(i)!=t.charAt(j)){
                        if (replaceFound){
                            return false;
                        }else{
                            replaceFound=true;
                        }
                    }
                    i++;
                    j++;
                }
                return replaceFound;
            }
            
            public boolean compare1(String s, String t){
                boolean insertFound = false;
                int i = 0; 
                int j = 0; 
                while(i<s.length() && j < t.length()){
                    if(s.charAt(i)!=t.charAt(j)){
                        if(insertFound){
                            return false;
                        }else{
                            insertFound = true;
                            if(s.length()>t.length()){
                                i++;
                            }else{
                                j++;
                            }
                        }
                    }else{ 
                        i++; j++;
                    }
                }
                return true;
            }

Log in to reply
 

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