LeetCode – One Edit Distance (Java)

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

Java Solution

public boolean isOneEditDistance(String s, String t) {
    if(s==null || t==null)
        return false;
 
    int m = s.length();
    int n = t.length();
 
    if(Math.abs(m-n)>1){
        return false;
    }
 
    int i=0; 
    int j=0; 
    int count=0;
 
    while(i<m&&j<n){
        if(s.charAt(i)==t.charAt(j)){
            i++;
            j++;
        }else{
            count++;
            if(count>1)
                return false;
 
            if(m>n){
                i++;
            }else if(m<n){
                j++;
            }else{
                i++;
                j++;
            }
        }
    }
 
    if(i<m||j<n){
        count++;
    }
 
    if(count==1)
        return true;
 
    return false;
}

2 thoughts on “LeetCode – One Edit Distance (Java)”

  1. private boolean isOneEditDist(String s1, String t1) {

    int l1 = s1.length();
    int l2 = t1.length();

    if (Math.abs(l1 – l2) == 2 || s1.equals(t1)) {
    return false;
    } else {
    for (int i = 0; i l2) {
    return s1.substring(i + 1).equals(t1.substring(i));
    } else if (l1 < l2) {
    return s1.substring(i).equals(t1.substring(i + 1));
    }
    }
    }
    }

    return Math.abs(l1 – l2) == 1;
    }

Leave a Comment