Very Easy to understand and Concise and Fast Solution - 6 lines


  • 0
    O
    1. scan from head of two strings until to index l where two characters are different.

    2. scan from tails of two strings until to index r1, r2 where two characters are different.

    3. y1 = r1 - l + 1, y2 = r2 - l + 1 are the different characters number

    4. y1, y2 should only be 1,0 or 0,1 or 1,1.

    I could have make the code shorter but I don't want to sacrifice clarity.

    Hope it helps.

    public class Solution {
        public boolean isOneEditDistance(String s, String t) {
            char[] c1 = s.toCharArray(), c2 = t.toCharArray();
            int l, r1, r2, len1 = c1.length, len2 = c2.length;
            for (l = 0; l < Math.min(len1, len2) && c1[l] == c2[l]; l++);
            for (r1 = len1 - 1, r2 = len2 - 1; r1 >= l && r2 >= l && c1[r1] == c2[r2]; r1--, r2--);
            int y1 = r1 - l + 1, y2 = r2 - l + 1;
            return y1 + y2 > 0 && y1 < 2 && y2 < 2;
        }
    }

Log in to reply
 

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