leetcode_161 相隔为 1 的编辑距离

274 阅读2分钟

要求

给定两个字符串 s 和 t,判断他们的编辑距离是否为 1。

注意:

满足编辑距离等于 1 有三种可能的情形:

  • 往 s 中插入一个字符得到 t
  • 从 s 中删除一个字符得到 t
  • 在 s 中替换一个字符得到 t 示例 1:
输入: s = "ab", t = "acb"
输出: true
解释: 可以将 'c' 插入字符串 s 来得到 t。

示例 2:

输入: s = "cab", t = "ad"
输出: false
解释: 无法通过 1 步操作使 s 变为 t。

示例 3:

输入: s = "1203", t = "1213"
输出: true
解释: 可以将字符串 s 中的 '0' 替换为 '1' 来得到 t。

核心代码

class Solution:
    def isOneEditDistance(self, s: str, t: str) -> bool:
        distance = len(s) - len(t)
        if abs(distance) > 1:
            return False
        if not s or not t:
            return s != t
        
        edit = 0
        i,j = 0,0
        while i < len(s) and j < len(t):
            if s[i] == t[j]:
                i += 1
                j += 1
            else:
                if edit:
                    return False

                if distance == 1: # 删除
                    i += 1
                elif distance == -1:  # 插入
                    j += 1
                else:   # 替换
                    i += 1
                    j += 1 
                edit += 1
        if i < len(s):
            return edit == 0
        if j < len(t):
            return edit == 0
        return i == len(s) and j == len(t) and edit == 1

image.png

解题思路:双指针,逐位判断,当编辑距离超过1的时候返回假.首先判断长度,长度差值超过1,编辑距离一定不是1,两者有一个为空返回真,两个都为空返回假,使用两个指针分别指向两个字符串,相同的情况,不断的向后移动,不同,我们看距离可以分成删除和插入,都不是就是替换,设置一个编辑的标志位,变成1,表示已经编辑过了,如果t或s没了,s或t还多了一位,取决于edit还是不是0,最终看编辑距离是不是1,即可。