One Edit Distance

Given two strings S and T, determine if they are both one edit distance apart.

这道题是之前那道Edit Distance的拓展,然而这道题并没有那道题难,这道题只让我们判断两个字符串的编辑距离是否为1,那么我们只需分下列三种情况来考虑就行了:

  1. 两个字符串的长度之差大于1或者s和t完全相同,那么直接返回False

  2. 两个字符串的长度之差等于1,那么把短的字符串加进去一个长字符串多余出的那个char,然后跳出循环,应该完全相同

  3. 两个字符串的长度之差等于0,那么两个字符串对应位置的字符只能有一处不同。

注意最后的corner case:s ="a", t = "",所以需要加上s == t[:-1]

class Solution(object):
    def isOneEditDistance(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """

        if s == t:
            return False
        l1, l2 = len(s), len(t)
        if l1 > l2: # force s no longer than t
            return self.isOneEditDistance(t, s)
        diff = l2-l1
        if diff > 1:
            return False
        for i in xrange(l1):
            if s[i] != t[i]:
                # 发现不等的时候,有两种情况:1.s和t长度相同只有一个char需要替换。2.长度相差一,则增加一个t里的char
                if l1 == l2:
                    s = s[:i]+t[i]+s[i+1:]  # replacement
                else:
                    s = s[:i]+t[i]+s[i:]    # insertion 
                # 只处理发现的第一个不同,然后就跳出循环,然后比较
                break
        return s == t or s == t[:-1]    # checking edge case for s ="a", t = ""

Last updated

Was this helpful?