1. 程式人生 > 其它 >劍指offer 8、青蛙跳臺階 python和c++

劍指offer 8、青蛙跳臺階 python和c++

72. 編輯距離

Difficulty: 困難

給你兩個單詞word1word2,請你計算出將word1轉換成word2所使用的最少運算元。

你可以對一個單詞進行如下三種操作:

  • 插入一個字元
  • 刪除一個字元
  • 替換一個字元

示例1:

輸入:word1 = "horse", word2 = "ros"
輸出:3
解釋:
horse -> rorse (將 'h' 替換為 'r')
rorse -> rose (刪除 'r')
rose -> ros (刪除 'e')

示例2:

輸入:word1 = "intention", word2 = "execution"
輸出:5
解釋:
intention -> inention (刪除 't')
inention -> enention (將 'i' 替換為 'e')
enention -> exention (將 'n' 替換為 'x')
exention -> exection (將 'n' 替換為 'c')
exection -> execution (插入 'u')

提示:

  • 0 <= word1.length, word2.length <= 500
  • word1word2 由小寫英文字母組成

Solution

Language: ****

class Solution:
  def minDistance(self, word1: str, word2: str) -> int:
    l1, l2 = len(word1), len(word2)
    if not l1 or not l2:
      return l1+l2
    # 初始化一個 (l1+1) * (l2+1) 大小的矩陣 
    dp = [[0] * (l2+1) for _ in range(l1+1)]
    # 初始化矩陣邊緣的編輯距離
    for i in range(l1+1):
      dp[i][0] = i
    for j in range(l2+1):
      dp[0][j] = j
    
    for i in range(1, l1+1):
      for j in range(1, l2+1):
        # 如果最後一個字元不相同
        if word1[i - 1] != word2[j - 1]:
          dp[i-1][j-1] += 1
        dp[i][j] = min(min(dp[i][j-1], dp[i-1][j]) + 1, dp[i-1][j-1])
    return dp[l1][l2]