字符串有三种编辑操作:插入一个字符、删除一个字符或者替换一个字符。 给定两个字符串,编写一个函数判定它们是否只需要一次(或者零次)编辑。
示例 1:
输入:
first = "pale"
second = "ple"
输出: True
示例 2:
输入:
first = "pales"
second = "pal"
输出: False
class Solution:
"""
解题思路:
1.先判断两个字符串长度是否相等
2.判断两个字符串长度的差值石佛等于1
1.找出字符串长度比较长的哪一个,当有值不相等时,去给长度长的那个字符串的索引值+1
"""
def oneEditAway(self, first: str, second: str) -> bool:
first_len = len(first)
second_len = len(second)
different_num = 0
if first_len == second_len:
if first_len == 1:
return True
for i in range(first_len):
if first[i] != second[i]:
different_num += 1
return False if different_num > 1 else True
elif abs(first_len-second_len) == 1:
if first_len == 0 or second_len == 0:
return True
first_index = 0
second_index = 0
if first_len > second_len:
first, second = second, first
first_len = len(first)
second_len = len(second)
while first_len > first_index and second_len > second_index:
if first[first_index] != second[second_index]:
different_num += 1
second_index += 1
else:
first_index += 1
second_index += 1
return False if different_num > 1 else True
else:
return False
|