[leetcode]One Edit Distance

用dp会超时。其实一遍循环就可以。

这段代码写的比较烂,其实如果分len(s)==len(t)和len(t)-1两种情况,就简单了。

class Solution:
    def isOneEditDistance(self, s: str, t: str) -> bool:
        if len(s) > len(t):
            s, t = t, s
        
        if len(t) - len(s) > 1:
            return False
        
        i = j = 0
        # distance = 0
        while i < len(s) and j < len(t) and s[i] == t[j]:
            i += 1
            j += 1
            
        if (len(t) - j)- (len(s) - i) == 1 and len(t) - 1 == j:
            return True
        
        x, y = i, j
        # distance = 1
        if y + 1 < len(t) and s[x] == t[y+1]:
            i, j = x, y + 1
            while i < len(s) and j < len(t) and s[i] == t[j]:
                i += 1
                j += 1
            if len(s) == i and len(t) == j:
                return True
            
        # distance = 1
        if (x + 1 < len(s) and s[x + 1] == t[y + 1]) or (x + 1 == len(s) and y + 1 == len(t)):
            i, j = x + 1, y + 1
            while i < len(s) and j < len(t) and s[i] == t[j]:
                i += 1
                j += 1
            if len(s) == i and len(t) == j:
                return True

  

原文地址:https://www.cnblogs.com/lautsie/p/12267881.html