Description
Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2.
You have the following three operations permitted on a word:
Insert a character
Delete a character
Replace a character
Example
Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation:
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')
Tips
0 <= word1.length, word2.length <= 500
word1 and word2 consist of lowercase English letters.
分析
简单的 dp 题目
def minDistance(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
N, M = len(word1), len(word2)
dp = [[N+M+2 for j in range(M+1)] for i in range(1+N)]
dp[0][0]
for i in range(1, N+1):
for j in range(1, M+1):
d = 1
if word1[i-1] == word2[j-1]:
d = 0
dp[i][j] = min(dp[i-1][j-1] +d , dp[i][j-1] + 1, dp[i-1][j] + 1)
return dp[-1][-1]
计算结果总是出错,主要是初始化出错了!! 没有初始化 dp[0][j] 和 dp[i][0]