Simple 4-liner Python Solution


  • 0
    Q

    The concept is relatively simple:
    Iterate through the minimum string, seeing if the char at i isn't equal. When this occurs, we know we need to do one of the following:

    • Replace a character at i (Compare the rest of the strings for match at i + 1)
    • Delete a character from s if its longer than t (Compare s[i:] to t[i + 1:]
    • Add a character to s if its shorter than t (Compare s[i + 1:] to t[i:])

    Finally, if none are different, we know that this can only be valid if s or t is missing a character at the end. Thus, check the lengths of the two to see if they're one away.

    def isOneEditDistance(self, s, t):
            for i in range(min(len(s), len(t))):
                if s[i] != t[i]:
                    return s[i + (len(s) >= len(t)):] == t[i + (len(s) <= len(t)):]
                
            return abs(len(s) - len(t)) == 1
    

Log in to reply
 

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