160. One Edit Distance

# Medium

题意:两个字符串st,要让s执行一次变换变成t

返回True,否则False,只有三种形式的变换:

  1. insert one char into s to get t, eg. "ab" -> "acb"

  2. delete one char from s to get t, eg. "abc" -> "ab"

  3. replace one char of s to get t, eg. "1203" -> "1213"

Solutions:

  1. if length difference is bigger than 1, return False

  2. if length difference is equal to 1, then only allow one char different, longer string moves to next char

  3. 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