Python solution with comments


  • 0
    V
        def isOneEditDistance(self, s, t):
            """
            :type s: str
            :type t: str
            :rtype: bool
            """
            #Classify as shorter/longer
            #Adding to shorter is the same as removing from longer
            shorter, longer= (s,t) if len(s) < len(t) else (t,s)
            #Two base cases handled
            if(len(longer)-len(shorter) > 1):
                return False
            if len(shorter) == 0 and len(longer) == 1:
                return True
            #Only one difference in characters is allowed
            one_difference = False
            i= 0 
            j = 0
            while(i < len(shorter)):
                #Go through short string see if we there is a difference, if there is mark dirty for once
                if shorter[i] != longer[j] and not one_difference:
                    one_difference = True
                    if len(shorter) < len(longer):
                        i -= 1
                #Second difference, we can stop
                elif shorter[i] != longer[j] and one_difference:
                    return False
                j += 1
                i += 1
            #Case where last char of longer string is the difference
            if(not one_difference):
                return len(longer)- len(shorter) == 1
            return one_difference
    

Log in to reply
 

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