Edit Distance
Description:
Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
Given word1 = “mart” and word2 = “karma”, return 3.
分析:
动态规划,下面给出证明。
最优子结构。
重叠子问题。
因为只涉及两个word之间的状态转换,所以是个二维dp,关键是如何得到递推关系。
可以假设dp[i][j]
是word1
的第前i-1
个字母和word2
的前j-1
个字母相互转化所需要的最少步数。分两种情况讨论:
word1[i-1] == word2[j-1]
,此时dp[i][j] = dp[i-1][j-1]
。(这里有个问题,就是目前本人无法证明dp[i-1][j-1] < dp[i][j-1] + 1
且dp[i-1][j-1] < dp[i-1][j] + 1
,请高人不吝指教。)word1[i-1] != word2[j-1]
,此时dp[i][j] = min(dp[i-1][j-1] + 1, dp[i][j-1] + 1, dp[i-1][j] + 1)
。
有了状态转换式,可以很容易的写出下面的代码。
代码如下:
1 | class Solution { |