[LeetCode] 72. Edit Distance 編輯距離 @python
阿新 • • 發佈:2019-02-17
Description
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:
Insert a character
Delete a character
Replace a character
給定兩個單詞 word1 和 word2,計算出將 word1 轉換成 word2 所使用的最少運算元 。
你可以對一個單詞進行如下三種操作:
- 插入一個字元
- 刪除一個字元
- 替換一個字元
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 1:
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')
Solution
典型的動態規劃問題。
首先定義狀態矩陣,dp[m][n]
,其中m
為word1的長度+1
,n
為word2的長度+1
,為什麼+1
?因為要考慮如果word1或word2為空的情況,後面可以看到。
定義dp[i][j]
為word1中前
插入操作:在word1
的前word2[j]
。這裡要考慮清楚,插入操作對於原word1
字元來說,word2
來說是前進了一位然後兩個字串才相等的。所以此時是dp[i][j]=dp[i][j-1]+1
。
刪除操作:在word1
的第word[:i-1]
與word2[:j]
相同。這裡要考慮清楚,刪除操作對於原word2
字元來說,word1
來說是刪除了一位然後兩個字串才相等的。所以此時是dp[i][j]=dp[i-1][j]+(0 or 1)
。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 27 16:48:29 2018
@author: saul
"""
class Solution:
def minDistance(self, word1, word2):
m=len(word1)+1; n=len(word2)+1
dp = [[0 for i in range(n)] for j in range(m)]
for i in range(n):
dp[0][i]=i
for i in range(m):
dp[i][0]=i
for i in range(1,m):
for j in range(1,n):
if word1[i-1] == word2[j-1]:
dp[i][j] = dp[i-1][j-1]
else:
dp[i][j] = min(dp[i][j-1], dp[i-1][j], dp[i-1][j-1]) + 1
return dp[m-1][n-1]
word1 = "intention"
word2 = "execution"
test = Solution()
print(test.minDistance(word1, word2))