序號 | 文獻 |
---|---|
1 | LeetCode 72. Edit Distance 最短字符串編輯距離 動態規劃 |
Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.python
You have the following 3 operations permitted on a word:ui
Example 1:code
Input: word1 = "horse", word2 = "ros" Output: 3 Explanation: horse -> rorse (replace 'h' with 'r') rorse -> rose (remove 'r') rose -> ros (remove 'e')
Example 2:rem
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')
這道題是求解字符串word1 經過替換,刪除,插入最小几步能夠變成word2。本題也能夠經過動態規劃的方式解決。設dp[i] [j] 是到word1的0 - i個字符經過替換,刪除,插入等步驟能夠變成Word2的0 - j 個字符的步驟數。則dp[i] [j] 的遞推式有:字符串
若是word1[ i - 1 ] 和word2[ j - 1 ] 相同,(注意這裏dp矩陣是從空字符開始,因此i-1是j -1 是真實的字符index),則當前的字符不用替換,那麼dp[i] [j] 的值就是dp[i-1] [j-1] 的值。get
若是word1[ i - 1 ] 和word2[ j - 1 ] 不相同,那麼要word1[ 0 - i ] 到word2[ 0 - j ]的方法有3種:刪除,替換,插入。則當前的值是這3個方法中的最小值:
2.1 刪除對應的是dp[ i - 1 ] [ j ] + 1,既word1[ 0 - i -1 ]已經能匹配 word2[ 0 - j ]了,因此刪除當前字符。
2.2 插入對應的是dp[ i ] [ j - 1 ] + 1 ,既word1[ 0 - i ] 已經能匹配wrod2[ 0 - j -1 ]了,當前必須在插入一個和word2[j]同樣的字符來轉換。
2.3 替換對應的是dp[ i - 1 ] [ j - 1 ] +1 ,既word1[ 0 - i -1 ]能匹配word2[ 0 - j -1 ]了,當前的word1[ i ] 和word2[ j ]不同,必須替換。it
同時必須初始化下第0行和第0列 ,(注意dp的0行和0列分別表明了2個空字符串):io
for i in range(1,row) : dp[i][0] = i for j in range(1,col): dp[0][j] = j
class Solution(object): def minDistance(self, word1, word2): """ :type word1: str :type word2: str :rtype: int """ row = len(word1) + 1 col = len(word2) + 1 dp = [ [ 0 for j in range(col) ] for i in range(row) ] if len(word1) == 0 : return len(word2) if len(word2) == 0 : return len(word1) dp[0][0] = 0 for i in range(1,row) : dp[i][0] = i for j in range(1,col): dp[0][j] = j for i in range(1,row): for j in range(1,col): if word1[i-1] == word2[j-1]: dp[i][j] = dp[i-1][j-1] else: dp[i][j] = min(dp[i-1][j-1] + 1, dp[i-1][j] + 1); dp[i][j] = min(dp[i][j-1] + 1, dp[i][j]) return dp[row-1][col-1]