One Edit Distance

medium, Array/String

Question

確定兩個字符串S和T是否是單一edit distance

Solution

假設len(S) = n, len(T) = m

  1. | n – m |>1, False
  2. 假設m<=n總是成立(otherwise, 交換S和T即可)
  3. m == n,如果可以修改一個字符達到S==T,True
  4. m<n, 插入一個字符達到S==T, True

Example
i. Modify operation – Modify a character to X in S.
S = “abcde”
T = “abXde”
ii. Insert operation – X was inserted before a character in S.
S = “abcde”
T = “abcXde”
iii. Append operation – X was appended at the end of S.
S = “abcde”
T = “abcdeX”

class Solution(object):
    def isOneEditDistance(self, s,t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        m, n = len(s), len(t)
        if m > n:
            s, t = t, s
        if n-m>1:
            return False
         i = 0
         shift = n-m
         while i < m and s[i] == t[i]:
              i+=1
          if i==m: return shift > 0
          if shift == 0: i+=1
          while i<m and s[i] == t[i+shift]:
              i+=1
          return i==m
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容