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长度相等。看s和t是否有且只有一个字母不相同。
- s比t多一个字母 或 s比t少一个字母。这两种情况逻辑其实是一样的,同时遍历s和t,当遇到第一个不同的字母,看后面的部分是否一样。如果一样,删除这个字母后
s=t
- 其他情况:s和t长度相差2以上,这样肯定不行。
class Solution(object):
def isOneEditDistance(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s) == len(t):
return sum(map(lambda c: s[c] != t[c], range(len(s)))) == 1
while s and t and s[0] == t[0]: # 注意前面的s and t条件,保证s和t不能为空。
s = s[1:]
t = t[1:]
if len(s) - len(t) == 1:
return s[1:] == t
elif len(t) - len(s) == 1:
return t[1:] == s
return False # 长度相差2以上的,直接返回False