关于leetcode:Leetcode面试题-0105-一次编辑-Python实现

  • 题目要求:

  • 思路:

    • 从左往右遍历两个字符串,如果遇到不同的字符,break
    • 从右往左遍历两个字符串,如果遇到不同的字符,break
    • 用左边不雷同的字符的下标-右边不雷同的字符的下标
    • 如果这两个字符串失去的两个差都小于1,返回True,否则返回False
  • 外围代码:
left1 = 0
        left2 = 0
        while left1 < len(first) and left2 < len(second):
            if first[left1] == second[left2]:
                left1 += 1
                left2 += 1
            else:
                break
        
        right1 = len(first) - 1
        right2 = len(second) - 1
        while right1 >= 0 and right2 >= 0:
            if first[right1] == second[right2]:
                right1 -= 1
                right2 -= 1
            else:
                break

        return right1 - left1 < 1 and right2 - left2 < 1
  • 残缺代码:
  • 如果两个字符串雷同,间接返回True
class Solution:
    def oneEditAway(self, first: str, second: str) -> bool:
        if first == second:
            return True
        
        left1 = 0
        left2 = 0
        while left1 < len(first) and left2 < len(second):
            if first[left1] == second[left2]:
                left1 += 1
                left2 += 1
            else:
                break
        
        right1 = len(first) - 1
        right2 = len(second) - 1
        while right1 >= 0 and right2 >= 0:
            if first[right1] == second[right2]:
                right1 -= 1
                right2 -= 1
            else:
                break

        return right1 - left1 < 1 and right2 - left2 < 1

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理