动态规划:将大问题分解为小问题。
用一个二维数组dp[i][j]表示word1的前i个字符匹配到word2的前j个字符需要几次操作。
class Solution(object):
def minDistance(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
m= len(word1)
n = len(word2)
dp = [[i+j for j in range(n+1)] for i in range(m+1)]
for i in range(1, m+1):
for j in range(1, n+1):
if word1[i-1] == word2[j-1]:
d = 0
else:
d =1
dp[i][j] = min(dp[i][j-1]+1, dp[i-1][j]+1, dp[i-1][j-1]+d)
return dp[m][n]