1. 程式人生 > >[LeetCode] 72. Edit Distance 編輯距離 @python

[LeetCode] 72. Edit Distance 編輯距離 @python

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

給定兩個單詞 word1word2,計算出將 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],其中mword1的長度+1nword2的長度+1,為什麼+1?因為要考慮如果word1word2為空的情況,後面可以看到。

定義dp[i][j]word1中前i個字元組成的串,與word2中前j個字元組成的串的編輯距離。

插入操作:在word1的前i個字元後插入一個字元,使得插入的字元等於新加入的word2[j]。這裡要考慮清楚,插入操作對於原word1字元來說,i是沒有前進的,而對於word2來說是前進了一位然後兩個字串才相等的。所以此時是dp[i][j]=dp[i][j-1]+1

刪除操作:在word1的第i1個字元後刪除一個字元,使得刪除後的字串word[:i-1]word2[:j]相同。這裡要考慮清楚,刪除操作對於原word2字元來說,j1是沒有前進的,而對於word1來說是刪除了一位然後兩個字串才相等的。所以此時是dp[i][j]=dp[i-1][j]+(0 or 1)

ifi==0andj==0,dp[i][j]=0(1) ifi==0andj>0,dp[i][j]=j(2) ifi>0andj==0,dp[i][j]=i(3) if0<imand0<jn,dp[i][j]=min(dp[i][j1]+1,dp[i1][j]+1,dp[i1][j1]+(0or1))(4)
#!/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))