Last updated
Was this helpful?
Last updated
Was this helpful?
Given two wordsword1_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:
Insert a character
Delete a character
Replace a character
Example
Given word1 ="mart"
and word2 ="karma"
, return3
.
这题还是建立一个二维的dp数组,多加一行一列给空串。初始化为下标,因为空串到现有字符串的edit distance就是现在这个串的长度。(eg.从空串变成abc,需要3个edit)当字母相等时,我们可以不用增加edit distance,把dp[i][j]赋值为左上角的值。如果我们发现不一样,证明我们需要改一下,我们取min(左边,上边,左上)+ 1。左边表示去掉一个,上边表示插入一个,左上表示改一个。