160. One Edit Distance
# Medium
题意:两个字符串s和t,要让s执行一次变换变成t
返回True,否则False,只有三种形式的变换:
insert one char into
sto gett, eg. "ab" -> "acb"delete one char from
sto gett, eg. "abc" -> "ab"replace one char of
sto gett, eg. "1203" -> "1213"
Solutions:
if length difference is bigger than 1, return False
if length difference is equal to 1, then only allow one char different, longer string moves to next char
if length difference is 0, then only allow one char different, both strings move to next char
class solution:
def isOneEditDistance(s: string, t: string):
n = len(s)
m = len(t)
if abs(n-m) > 1:
return False
if n - m == 1:
for i in range(n):
if s[i] != t[i]:
return s[i+1:] == t[i:]:
elif m - n == 1:
for i in range(m):
if s[i] != t[i]:
return s[i:] != t[i+1:]:
elif m == n:
for i in range(n):
if s[i] != t[i]:
return s[i+1:] != t[i+1:]:Last updated
Was this helpful?