One Edit Distance

Problem: One Edit Distance

It's apparent that one-edit-distance strings have only one letter difference. We can use two pointers, one to head and one to tail, both going to the middle. Once we got difference at the same pointer, both pointers should add up to length of smaller string.

Code in Python:

class Solution(object):
    def isOneEditDistance(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        ls, lt = len(s), len(t)
        if abs(ls-lt) > 1: return False

        i, j, k = 0, 0, min(ls, lt)
        while i < k and s[i] == t[i]:
            i += 1
        while j < k-i and s[~j] == t[~j]:
            j += 1

        return max(ls, lt) - 1 == i + j

results matching ""

    No results matching ""