一、题目描述
- 给定两个单词 word1 和 word2,计算出将 word1 转换成 word2 所使用的最少操作数 。你可以对一个单词进行如下三种操作:
- 插入一个字符
- 删除一个字符
- 替换一个字符
示例 1:
输入: word1 = "horse", word2 = "ros"
输出: 3
解释:
horse -> rorse (将 'h' 替换为 'r')
rorse -> rose (删除 'r')
rose -> ros (删除 'e')
示例 2:
输入: word1 = "intention", word2 = "execution"
输出: 5
解释:
intention -> inention (删除 't')
inention -> enention (将 'i' 替换为 'e')
enention -> exention (将 'n' 替换为 'x')
exention -> exection (将 'n' 替换为 'c')
exection -> execution (插入 'u')
二、解题思路
- 边界条件:如果一个字符串是空的,另外一个不是,需要的操作次数为不空的串的长度
- 计算方法:
- ~ 转换到 ~ 需要 步,那么如果 ,就不用操作了,最终需要 步;否则还得改最后那个,需要 步;
- ~ 转换到 ~ 需要 步,那么将 再删掉即可,最终需要 步
- ~ 转换到 ~ 需要 步,那么如果 ,那么将 再插入即可,最终需要 步
- 取上述三个步骤的最小值
三、图例
四、最终代码
class Solution {
public:
int minDistance(string word1, string word2) {
auto m = word1.size();
auto n = word2.size();
vector<vector<int>> cost(m + 1, vector<int>(n + 1));
for (int i = 0; i <= m; i++)
cost[i][0] = i;
for (int i = 0; i <= n; i++)
cost[0][i] = i;
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
cost[i][j] = (word1[i - 1] == word2[j - 1] ? cost[i - 1][j - 1] : (1 + min(cost[i - 1][j], min(cost[i - 1][j - 1], cost[i][j - 1]))));
return cost[m][n];
}
};
五、运行结果
同样的代码,谜一样的运行差距