检查Python中两个字符串之间的编辑距离是否为一
假设我们有两个字符串s和t。我们必须检查s和t之间的编辑距离是否正好为1。这里两个字符串之间的编辑意味着这三个字符串中的任何一个-
插入一个字符
删除字符
替换字符
因此,如果输入类似于s=“hello”t=“heillo”,则输出将为True,因为我们需要在s中插入一个字符以获取t。
示例
让我们看下面的实现以更好地理解-
def solve(s, t):
if abs(len(s) - len(t)) > 1:
return false
edit_dist_cnt = 0
i = 0
j = 0
while i < len(s) and j < len(t):
if s[i] != t[j]:
if edit_dist_cnt == 1:
return false
if len(s) > len(t):
i += 1
elif len(s) < len(t):
j += 1
else:
i += 1
j += 1
edit_dist_cnt +=1
else:
i += 1
j += 1
if i < len(s) or j < len(t):
edit_dist_cnt += 1
return edit_dist_cnt == 1
s = "hello"
t = "heillo"
print(solve(s, t))输入值
"hello", "heillo"
输出结果
True
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短