给定两个字符串 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。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/one-edit-distance
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
第一种思路:
既然已经做过了LeetCode-Python-72. 编辑距离,那么直接调用然后算一下编辑距离是不是1就行了。
缺点:稳定超时……
class Solution(object):
def isOneEditDistance(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
return self.minDistance(s, t) == 1
def minDistance(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
#dp[i][j]表示word1[:i + 1]和word2[:j + 1]的解
l1, l2 = len(word1), len(word2)
dp = [[0 for _ in range(l2 + 1)] for _ in range(l1 + 1)]
for i in range(l1 + 1):
dp[i][0] = i
for j in range(l2 + 1):
dp[0][j] = j
for i in range(1, l1 + 1):
for j in range(1, l2 + 1):
if word1[i - 1] == word2[j - 1]:
dp[i][j] = dp[i - 1][j - 1]
else:
dp[i][j] = 1 + min(dp[i - 1][j], dp[i - 1][j - 1], dp[i][j - 1])
return dp[l1][l2]
第二种思路:
双指针,逐位判断,当编辑距离超过1的时候返回假。
class Solution(object):
def isOneEditDistance(self, s, t):
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): #如果t没了,s还多了一位,取决于edit还是不是0
return edit == 0
if j < len(t): #如果s没了,t还多了一位,取决于edit还是不是0
return edit == 0
return i == len(s) and j == len(t) and edit == 1