原题
Given two strings s and t, determine if they are both one edit distance apart.
Note:
There are 3 possiblities to satisify one edit distance apart:
Insert a character into s to get t
Delete a character from s to get t
Replace a character of s to get t
Example 1:
Input: s = “ab”, t = “acb”
Output: true
Explanation: We can insert ‘c’ into s to get t.
Example 2:
Input: s = “cab”, t = “ad”
Output: false
Explanation: We cannot get t from s by only one step.
Example 3:
Input: s = “1203”, t = “1213”
Output: true
Explanation: We can replace ‘0’ with ‘1’ to get t.
解法
根据题意, s能转化为t的条件是两个的长度的差不超过1, 因此先排除那些长度的差大于1的情况. 然后分类讨论, 尝试将s变为t.
代码
class Solution(object):
def isOneEditDistance(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
len_s, len_t = len(s), len(t)
if not(len_s - len_t in [-1, 0, 1]):
return False
s, t = list(s), list(t)
if len_s < len_t:
# try to insert a char to get t
for i, ch in enumerate(s):
if s[i] != t[i]:
s.insert(i, t[i])
# check if they are equal
return s == t
return True
if len_s == len_t:
for i, ch in enumerate(s):
if s[i] != t[i]:
s[i] = t[i]
return s == t
if len_s > len_t:
# try to delete a char
for i, ch in enumerate(t):
if s[i] != t[i]:
s.pop(i)
return s == t
return True
一编辑距离
本文探讨了判断两个字符串是否可以通过一次插入、删除或替换操作达到一编辑距离的方法。通过分类讨论并提供示例,展示了如何实现这一功能。
270

被折叠的 条评论
为什么被折叠?



