- 题目要求:
思路:
- 从左往右遍历两个字符串,如果遇到不同的字符,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