zoukankan      html  css  js  c++  java
  • [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
    

      

  • 相关阅读:
    对我影响最大的三位老师
    自我介绍
    第二周作业
    2019第一次作业
    PTA编程总结3
    币值转换
    PTA编程总结2
    PTA编程总结1
    秋季学期学习总结
    人生路上对你影响最大的三位老师
  • 原文地址:https://www.cnblogs.com/lautsie/p/12267881.html
Copyright © 2011-2022 走看看