72. 编辑距离
题目:给你两个单词 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) {
int n = word1.size();
int m = word2.size();
//有一个字符串为空串
if(n*m == 0) return n+m;
//定义DP数组
int DP[n+1][m+1];
//初始化边界状态
for(int i = 0; i < n+1; i++)
DP[i][0] = i;
for(int j = 0; j < m+1; j++)
DP[0][j] = j;
//两层for循环遍历所有DP值
for(int i = 1; i < n+1; i++)
{
for(int j = 1; j < m+1; j++)
{
int left = DP[i-1][j] + 1;
int down = DP[i][j-1] + 1;
int leftdown = DP[i-1][j-1];
if(word1[i-1] != word2[j-1]) leftdown += 1;
DP[i][j] = min(left, min(down, leftdown));
}
}
return DP[n][m];
}
};
本文介绍了一个经典的字符串处理问题——编辑距离。通过实例演示了如何计算两个字符串之间的最小操作数,包括插入、删除和替换操作。提供了详细的算法实现过程及代码示例。

3336

被折叠的 条评论
为什么被折叠?



