LeetCode 72 Edit Distance(Python詳解及實現)
【題目】
Given two words word1 and word2, find theminimum number of steps required to convert word1 to word2. (each operation iscounted as 1 step.)
You have the following 3 operationspermitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character
word1最少經過多少步可以變成word2。word1允許的操作如下:
a)插入一個字元;
b)刪除一個字元;
c)替換一個字元。
比如“abc”變成“aba”只需要用"a"將最後一個字元"c"替換掉就可以。此時distance = 1
如word1[i] == word2[j],只需把word1[0至i-1]變為word2[0至j-1]。此時res[i][j] = res[i-1][j-1]
【思路】
l 替換:
若word1[i]替換為word2[j]是從word1到word2的最小改動,則需先把word1[0至i-1]以最小距離變為word2[0至j-1],然後在執行替換操作,此時res[i][j] = res[i-1][j-1] + 1
l 插入:
若word1[i]插入某字元為是從word1到word2的最小改動,則需先把word1[0至i-1]以最小距離變為word2[0至j-1],然後在執行插入操作,此時res[i][j] = res[i-1][j-1] + 1
l 刪除:
若word1[i]刪除某字元是從word1到word2的最小改動,則需先把word1[0至i-1]以最小距離變為word2[0至j-1],然後在執行插入操作,此時res[i][j] = res[i-1][j-1] + 1
【Python實現】
class Solution:
#@return an integer
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)]#(m+1)*(n+1)二維矩陣
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):
dp[i][j]=min(dp[i-1][j]+1,dp[i][j-1]+1, dp[i-1][j-1]+(0 if word1[i-1]==word2[j-1] else 1))
return dp[m-1][n-1]
s = Solution()
s.minDistance("bird","ibdr")