1ms Java Solution, checking both ends


  • 0
    H

    public class Solution {

    public boolean isOneEditDistance(String s, String t) {
        // if the difference of length is equal or larger than 2, it's impossible to only use one edit
        if (Math.abs(s.length() - t.length()) >= 2 || s.equals(t)) return false;
        // this method is valid for s.length() >= t.length(), if not, change the input order
        if (s.length() < t.length()) return isOneEditDistance(t, s);
        char[] sChar = s.toCharArray();
        char[] tChar = t.toCharArray();
        int sL = sChar.length, tL = tChar.length;
        int sRight = sL - 1, tRight = tL - 1, sLeft = 0, tLeft = 0;
        int count = sChar.length; // use count to store the number of difference
        // start from the right end as well as checking if the characters in two strings are the same, and update the count
        while (sRight >= 0 && tRight >= 0 && sChar[sRight] == tChar[tRight]) {
            sRight--;
            tRight--;
            count--;
        }
        // then start from left to the right above to do the same thing
        while (sLeft <= sRight && tLeft <= tRight && sChar[sLeft] == tChar[tLeft]) {
            sLeft++;
            tLeft++;
            count--;
        }
        // check if the count is 1
        return count == 1;
    }
    

    }


Log in to reply
 

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