1. 程式人生 > >【LeetCode每天一題】Edit Distance(編輯距離)

【LeetCode每天一題】Edit Distance(編輯距離)

soft replace object 技術分享 大小 rac 個數字 當前位置 cte

  Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.You have the following 3 operations permitted on a word:

  1. Insert a character
  2. Delete a character
  3. Replace a character

Example 1:

  Input: word1 = "horse", word2 = "ros"
  Output: 3
  Explanation: 
  horse -> rorse (replace ‘h‘ with ‘r‘)
  rorse -> rose (remove ‘r‘)
  rose -> ros (remove ‘e‘)

Example 2:

  Input: word1 = "intention", word2 = "execution"
  Output: 5
  Explanation: 
  intention -> inention (remove ‘t‘)
  inention -> enention (replace ‘i‘ with ‘e‘)
  enention -> exention (replace ‘n‘ with ‘x‘)
  exention -> exection (replace ‘n‘ with ‘c‘)
  exection -> execution (insert ‘u‘)

思路

   這道題是一道典型的使用動態規劃來解決的題目。兩個單詞我們申請一個(m+1)*(n+1)的矩陣,首先對矩陣的第一行和第一列進行初始化,然後從第二行第二個位置開始進行遍歷,每次得到最小的編輯數。 這裏如果當前兩個字母相等的話,直接使其等於上一個字母的編輯數,也即dp[i][j] = dp[i-1][j-1]。但是當兩個字母不相等的時候,我們可以從左邊上邊和右上角選出最小的編輯數在加一,得到當前位置的編輯數,也即dp[i][j] = min(dp[i-1][j-1], min(dp[i-1][j], dp[i][j-1]))+1。這樣直到循環遍歷到矩陣的末尾。最後一個數字也即是最小編輯距離。時間復雜度為O(m*n),空間復雜度為O(m*n)。

  一般對於動態規劃來題目來說,我們除了設置一個(m+1)*(n+1)的矩陣外,還可以使用(n+1)大小的矩陣。這裏動態方程還是一樣的,只不過這裏我們需要處理的細節更多一些。時間復雜度和上面的一樣,空間復雜度為O(n+1)。
圖示步驟

    技術分享圖片解決代碼
  第一種空間復雜度為O(m*n)的解法
 1 class Solution(object):
 2     def minDistance(self, word1, word2):
 3         """
 4         :type word1: str
 5         :type word2: str
 6         :rtype: int
 7         """
 8         if not word1 or not word2:          # 一個為空直接返回另一個不為空的長度。
 9             return len(word1) if not word2 else len(word2)
10         
11         m, n= len(word1), len(word2)
12         dp = []
13         for i in range(m+1):            # 構造輔助矩陣
14             dp.append([0]*(n+1))        
15         
16         for i in range(1, m+1):       # 初始化第一列
17             dp[i][0] = i
18         
19         for j in range(1, n+1):         # 初始化第一行
20             dp[0][j] = j
21         
22         for i in range(1, m+1):           # 逐個求解
23             for j in range(1, n+1):
24                 if word1[i-1] == word2[j-1]:        # 當前字母相等時,
25                     dp[i][j] = dp[i-1][j-1]
26                 else:                              # 不相等時
27                     dp[i][j] = min(dp[i-1][j-1], min(dp[i-1][j], dp[i][j-1]))+1
28         return dp[m][n]

  空間復雜度為O(n)的解法
 1 class Solution(object):
 2     def minDistance(self, word1, word2):
 3         """
 4         :type word1: str
 5         :type word2: str
 6         :rtype: int
 7         """
 8         if not word1 or not word2:
 9             return len(word1) if not word2 else len(word2)
10         m, n= len(word1), len(word2)
11         dp = [0]*(n+1)                       #  申請輔助數據 
13         for i in range(1, n+1):             # 初始化第一行
14             dp[i] = i
15         
16         for i in range(1,m+1):              # 循環遍歷
17             pre = dp[0]                     # 記錄下dp[0]的值,也即為上面矩陣中dp[i-1][j-1]的值。
18             dp[0]= i                         # 給dp[0]賦值為當前單詞編輯列的距離,也就是上面的初始化第一列
19             for j in range(1, n+1): 
20                 tem = dp[j]                     # 相當於記錄下dp[i][j-1]的值,
21                 if word1[i-1] == word2[j-1]:        # 單詞相等的時候
22                     dp[j] = pre                 
23                 else:
24                     dp[j] = min(pre, min(dp[j-1], dp[j]))+1
25                 pre = tem                   # 更新值
26                 
27         return dp[-1]
28             





【LeetCode每天一題】Edit Distance(編輯距離)