题目
字符串有三种编辑操作:插入一个字符、删除一个字符或者替换一个字符。给定两个字符串,编写一个函数判断它们是否只需要一次(或者零次)编辑。
思路
- 长度相差超过1位,返回False
- 长度相差1位(判断是否有插入、删除),双指针
- 第一次碰到字符不一样,短字符串指针不动,长字符串指针+1;第二次碰到则返回False
- 长度相等(判断是否有替换操作)
- 第一次碰到字符不一样,短字符串指针+1,长字符串指针+1
class Solution:
def oneEditAway(self, first: str, second: str) -> bool:
if first == second: return True
# len(first) > len(second)
if len(first) < len(second):
first, second = second, first
if len(first) - len(second) > 1:
return False
i, j = 0, 0
flag = False
times = 0
if len(first) == len(second):
while i < len(first) and j < len(second):
if first[i] != second[j] and times < 1:
flag = not flag # 布尔值取反
times += 1
elif first[i] != second[j] and times >= 1:
return False
i += 1
j += 1
return flag
else:
# 相差1
while i < len(first) and j < len(second):
if first[i] != second[j] and times < 1:
flag = not flag
times += 1
i += 1
elif first[i] == second[j]:
i += 1
j += 1
else:
# times == 1
return False
return True
- 第一次碰到字符不一样,短字符串指针+1,长字符串指针+1
还可以用动态规划来解答。
- 留坑,回头来填