Purely comparing with Two-pointers with no substring - Java Solution


  • 0
    A
    public boolean isOneEditDistance(String s, String t) {
            int sLen = s.length();
            int tLen = t.length();
            if (Math.abs(sLen - tLen) > 1) return false;
            
            int i = 0, j = 0;
            int edits = 0;
            
            while (i < sLen && j < tLen) {
                if (s.charAt(i) != t.charAt(j)) {
                    edits++;
                    // skip char on the longer str
                    if (sLen >= tLen) i++;
                    if (sLen <= tLen) j++;
                } else {
                    i++;
                    j++;
                }
            }
            
            // leftovers
            edits += tLen - j;
            edits += sLen - i;
            
            return edits == 1;
        }
    

Log in to reply
 

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