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中前
i
个字符组成的串,与word2中前
插入操作:在word1
的前
i
个字符后插入一个字符,使得插入的字符等于新加入的word2[j]
。这里要考虑清楚,插入操作对于原word1
字符来说,word2
来说是前进了一位然后两个字符串才相等的。所以此时是dp[i][j]=dp[i][j-1]+1
。
删除操作:在word1
的第
i−1
个字符后删除一个字符,使得删除后的字符串word[:i-1]
与word2[:j]
相同。这里要考虑清楚,删除操作对于原word2
字符来说,
j−1
是没有前进的,而对于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))