Python O(N), no extra space or list slicing, 56ms


  • 0
    Y
    class Solution(object):
        def isOneEditDistance(self, s, t):
            ln_s = len(s)
            ln_t = len(t)
            
            if abs(ln_s - ln_t) > 1:
                return False
            if max(ln_t, ln_s) == 1 and ln_t != ln_s:
                return True
            
            i = 0
            j = 0
            error = 0
            while i < ln_s and j < ln_t:
                if s[i] != t[j]:
                    error += 1
                    if ln_s > ln_t:
                        i += 1
                    elif ln_s < ln_t:
                        j += 1
                    else:
                        i += 1
                        j += 1
                else:
                    i += 1
                    j += 1
                
            return error == 1 or (error == 0 and abs(ln_s - ln_t) == 1)

Log in to reply
 

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