Python concise solution with comments.


  • 15
    C
    def isOneEditDistance(self, s, t):
        if s == t:
            return False
        l1, l2 = len(s), len(t)
        if l1 > l2: # force s no longer than t
            return self.isOneEditDistance(t, s)
        if l2 - l1 > 1:
            return False
        for i in xrange(len(s)):
            if s[i] != t[i]:
                if l1 == l2:
                    s = s[:i]+t[i]+s[i+1:]  # replacement
                else:
                    s = s[:i]+t[i]+s[i:]  # insertion
                break
        return s == t or s == t[:-1]

  • 0
    O

    if l1 > l2: # force s no longer than t
    return self.isOneEditDistance(t, s) ==> love these lines!


  • 15
    O

    P.S. It would be quicker if you reduce the if/else when s[i] != t[i]

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

  • 0

    @orbuluh but his is code is more readable than yours!!!!


  • 0

    @orbuluh
    you could learn from my code :

    class Solution(object):
        def isOneEditDistance(self, s, t):
            if s == t:
                return False 
            l1,l2 = len(s),len(t)
            if l2 - l1 > 1 or l1 - l2 >1:
                return False
            for i in range(min(len(s),len(t))):
                if s[i] != t[i]:
                    if l1 == l2:
                        s = s[:i] + t[i] + s[i+1:] # subsitution
                    elif l2 > l1:
                        s = s[:i] + t[i] + s[i:]   # insertion
                    else:
                        s = s[:i] + s[i+1:]        # deletion
                    break
            return s == t or s == t[:-1] or s[:-1] == t # checking edge case for s ="a", t = ""
    

  • 0
    L
    This post is deleted!

  • 0
    C

    @orbuluh said in Python concise solution with comments.:

    if abs(len(s) - len(t)) > 1 or s == t: return False

    abs() would not be necessary, since you swapped the lengths in the previous line. Just if (len(t)-len(s))>1 is ok. Thanks for a great solution, though.


Log in to reply
 

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