160. One Edit Distance

# Medium

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

Was this helpful?