检查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

以上是 检查Python中两个字符串之间的编辑距离是否为一 的全部内容, 来源链接: utcz.com/z/340711.html

回到顶部