Premiumlab  

https://leetcode.com/problems/one-edit-distance/#/description

 

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

 

 

Sol: 

 

In computational linguistics and computer scienceedit distance is a way of quantifying how dissimilar two strings (e.g., words) are to one another by counting the minimum number of operations required to transform one string into the other. 

 

If s and t are one distance away then no matter it is insert or delete or replace the count of common characters must be max(m, n) - 1, where m is the length of sand n is the length of t. It is easy to see that the reverse is also true.

Assume the length of common prefix (from left to right) is i and the length of common suffix after i (from right to left) is j, the answer is then max(m, n) - 1 == i + j

Example 1 (1 replace)

s = "abcdefg", m = 7
t = "abcxefg", n = 7 
i = 3, j = 3
max(m, n) - 1 == i + j is true

Example 2 (0 edit)

s = "abcdefg", m = 7
t = "abcdefg", n = 7 
i = 7, j = 0
max(m, n) - 1 == i + j is false

Example 3 (1 insert)

s = "abcdefg", m = 7
t = "abcefg", n = 6 
i = 3, j = 3
max(m, n) - 1 == i + j is true

Example 4 (1 delete 1 insert)

s = "abcdefg", m = 7
t = "abcefgh", n = 7 
i = 3, j = 0
max(m, n) - 1 == i + j is false

The method is O(m+n) since any character is visited at most once.

 

 

 

 

class Solution(object):
    def isOneEditDistance(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        
        if abs(len(s) - len(t)) > 1:
            return False
        min_len = min(len(s), len(t))
        
        left = right = 0
        
        while left < min_len and s[left] == t[left]:
            left += 1
        
        while right < min_len - left and s[~right] == t[~right]:
            right += 1
        
        return max(len(s), len(t)) - (left + right) == 1
        

 

 

 

Note: 

 

1 The usage of ~ in Python string operation. 

 

ex. a= [1,2,3,4,5,6]

 

i = 1

a[i] =  2

a[~i] = 5

 

 

Sol 2:

 

class Solution(object):
    def isOneEditDistance(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        
        if len(s) > len(t):
            return self.isOneEditDistance(t,s)
        
        if abs(len(s) - len(t)) > 1 or s == t:
            return False
        
        for i in range(len(s)):
            if s[i] != t[i]:
                # check replacement or deletion operation
                return s[i+1:] == t[i+1:] or s[i:] == t[i+1:]
        return True
        

 

posted on 2017-07-06 14:09  Premiumlab  阅读(222)  评论(0编辑  收藏  举报