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