简繁EN

LeetCodeNo. 091

【LeetCode with Python】 72. Edit Distance

目錄

題目

原題頁面:https://leetcode.com/problems/edit-distance/
題目型別:Dynamic Programming, String
難度評價:Hard
類似題目:(M) One Edit Distance

Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)

You have the following 3 operations permitted on a word:

a) Insert a character
b) Delete a character
c) Replace a character


分析

一道傳統意義上的經典的動態規劃題目。注意動態規劃十有八九可以最佳化空間複雜度,不是真的要開闢一個(m+1)(n+1)的大矩陣出來。目前用的解法已經減小到了兩行,還可以繼續最佳化到一行(外加一個變數記住左上角的值),但最佳化不到22的小矩陣:算每一格都要用到上一行同一列的值,這一行算完之前,上一行後面那些格子都還得留著。
對於這個DP矩陣,每個方格代表當前子問題的最佳解決方案。如果每個方格記錄下自身是基於如何從上一層子問題的最佳解決方案推進而來,則通過這層線索,可以從指定的一個方格,反向推演出當前最佳方案的整個構成路徑。如果一個方法的最佳解決方案不只一個,則構成路徑變成了一棵樹。
DP矩陣的第0行和第0列一般都要特別處理。
此外,DP的題目最好能習慣於寫出DP遞推方程,這樣可以用更簡潔的公式來解釋思路:

  1. d[0, j] = j
  2. d[i, 0] = i
  3. d[i, j] = d[i-1, j - 1] if A[i] == B[j]
  4. d[i, j] = min(d[i-1, j - 1], d[i, j - 1], d[i-1, j]) + 1 if A[i] != B[j]

程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution:
# @return an integer
def minDistance(self, word1, word2):
if "" == word1 and "" == word2:
return 0
elif "" == word1:
return len(word2)
elif "" == word2:
return len(word1)
len1 = len(word1)
len2 = len(word2)
arr1 = [0 for y in range(0, len1 + 1)]
arr2 = [0 for y in range(0, len1 + 1)]
arr1[0] = 0
for y in range(1, len1 + 1):
arr1[y] = y
for x in range(1, len2 + 1):
arr2[0] = x
for y in range(1, len1 + 1):
arr2[y] = min(arr1[y - 1] + (0 if (word1[y - 1] == word2[x - 1]) else 1), arr1[y] + 1, arr2[y - 1] + 1)
tmp = arr1
arr1 = arr2
arr2 = tmp
for y in range(0, len1 + 1):
arr2[y] = 0
return arr1[len1]

本文地址:https://xnerv.wang/zh-tw/leetcode-edit-distance/