Clean Python solution beat 57%


  • 0
    H

    Refer from CtCi189, Problem 1.5. Deletion is equivalent to insertion with s and t swapped.

    class Solution(object):
        def isOneEditDistance(self, s, t):
            """
            :type s: str
            :type t: str
            :rtype: bool
            """
            def isReplacable(s, t):
                error = False
                for i, c in enumerate(s):
                    if s[i]!=t[i]:
                        if error: return False
                        error = True
                return True
            
            def isInsertable(s, t):
                error = False
                index1, index2 = 0, 0
                n_s, n_t = len(s), len(t)
                while (index1 < n_s and index2 < n_t):
                    if s[index1] != t[index2]:
                        if error: return False
                        error = True
                        index2 += 1
                    else:
                        index1 += 1
                        index2 += 1
                return True
            
            if s == t: return False
            if (len(s) == len(t)):
                return isReplacable(s, t)
            elif (len(s) + 1 == len(t)):
                return isInsertable(s, t)
            elif (len(s) - 1 == len(t)):
                return isInsertable(t, s)
            return False
    

Log in to reply
 

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