问题
给定两个单词,找出能把word1变为word2的最小操作个数,允许操作有:对单个字符插入/删除/替换。
Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation:
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')
思路
用dp[i][j]表示word1[:i]和word2[:j]之间的解(考虑到dp要放置0字符的状态)。dp方程为:
如果word1[i] == word2[j],两字符相等,不需要任何操作,显然dp[i][j] = dp[i-1][j-1]。
否则,要在原来的基础上进行插入或替换,在dp[i-1][j]或dp[i][j-1]的基础插入,或者在dp[i-1][j-1]的基础替换,所以有dp[i][j] = min(dp[i - 1][j], dp[i][j - 1], dp[i-1][j-1]) + 1。
时间复杂度O(n*m),空间复杂度O(n*m)
代码
class Solution(object):
def minDistance(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
dp = [ [i+j for j in range(len(word2)+1)] for i in range(len(word1)+1)]
for i in range(1,len(word1)+1):
for j in range(1,len(word2)+1):
if(word1[i-1] == word2[j-1]):
dp[i][j] = dp[i-1][j-1]
else:
dp[i][j] = min(dp[i - 1][j], dp[i][j - 1], dp[i-1][j-1]) + 1
return dp[len(word1)][len(word2)]