力扣72题 字符串编辑距离 C++
动态规划
输入: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')
int minDistance(string word1, string word2) {
int len1=word1.size();
int len2=word2.size();
int dp[len1+1][len2+1];
for(int i=0;i<len1+1;i++){
dp[i][0]=i;
}
for(int j=0;j<len2+1;j++){
dp[0][j]=j;
}
for(int i=1;i<=len1;i++){
for(int j = 1;j<=len2;j++){
int diff=1;
if(word1[i-1]==word2[j-1]){
diff=0;
}
int temp=min(dp[i][j-1]+1,dp[i-1][j]+1);
dp[i][j]=min(temp,dp[i-1][j-1]+diff);
}
}
return dp[len1][len2];
}
第一篇笔记还需要多多练习,刷题才能变得更强
C++语法还需要加强,在写题中训练,熟能生巧。
1. C++中的min max abs 直接用
2. 变量名count 要写成cnt
本文介绍了如何使用C++实现力扣72题——字符串编辑距离的动态规划解决方案。通过示例详细解释了算法过程,包括替换、删除和插入操作,并在代码中展示了如何利用min函数优化计算。作者指出,对于C++语法的掌握仍需加强,并通过不断刷题来提升编程技能。

937

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



