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

2次阅读

共计 787 个字符,预计需要花费 2 分钟才能阅读完成。

  • 题目要求:

  • 思路:

    • 从左往右遍历两个字符串,如果遇到不同的字符,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
正文完
 0