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