解法:
推荐解法和我的解法看似类似,时间、空间复杂度非常接近,但实则简洁很多。究其原因,推荐方法中采用了分段的思想。这种分段的思想很适合于字符串问题。
Python源码:
Runtime: 24 ms, faster than 28.87% of Python online submissions for One Edit Distance.
Memory Usage: 11.8 MB, less than 88.24% of Python online submissions for One Edit Distance.
class Solution(object):
def isOneEditDistance(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
m = len(s)
n = len(t)
if m > n:
return self.isOneEditDistance(t, s)
if n - m > 1:
return False
i = 0
shift = n-m
while(i < m and s[i] == t[i]):
i += 1
if shift == 0:
i += 1
while(i < m and s[i] == t[i + shift]):
i += 1
return i == m
我的心路:
有空字符串的情况判断后。分两种情况,一种是两个字符串等长,一种是一长一短。首先保留一个布尔值edited=False,第一次发现不同时置为True,第二次发现不同时直接返回False;如果长度不等,edit为False时需要考虑最终长的字符串长度与遍历符j大小相差1的情况。
Runtime: 24 ms, faster than 28.74% of Python online submissions for One Edit Distance.
Memory Usage: 11.9 MB, less than 52.94% of Python online submissions for One Edit Distance.
class Solution(object):
def isOneEditDistance(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s)+len(t) == 0:
return False
elif len(s)+len(t) == 1:
return True
edited = False
i = 0
j = 0
if len(s) < len(t):
longer = t
shorter = s
else:
longer = s
shorter = t
if len(s) == len(t):
while i <= len(s) - 1:
if s[i] != t[j]:
if edited:
return False
edited = True
i += 1
j += 1
else:
while i <= len(shorter) - 1:
if shorter[i] != longer[j]:
if edited:
return False
else:
i -= 1
edited = True
i += 1
j += 1
if (edited and len(longer) - j == 0) or (edited == False and len(s) != len(t) and len(longer) - j == 1):
return True
else:
return False