题解 | 计算字符串的编辑距离

计算字符串的编辑距离

https://www.nowcoder.com/practice/3959837097c7413a961a135d7104c314?tpId=37&tags=&title=&difficulty=3&judgeStatus=&rp=1&sourceUrl=%2Fexam%2Foj%2Fta%3FtpId%3D37&gioEnter=menu

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
//动态规划是用二维思维去解决二维问题
/*步骤:
1.问题结构分析
2.递推关系建立-构建状态转移方程例如:dp[i] = dp[i-1] + dp[i-2]
3.自底向上计算
4.最优方案追踪
*/
int main() {
    string str1, str2;
    while (cin >> str1 >> str2) { // 注意 while 处理多个 case
        vector<vector<int>>dp(str1.size() + 1, vector<int>(str2.size() + 1, 0));
        for (int i = 1; i < str1.size() + 1; i++) {
            dp[i][0] = i;
        }
        for (int j = 1; j < str2.size() + 1; j++) {
            dp[0][j] = j;
        }
        for (int i = 1; i < str1.size() + 1; i++) {
            for (int j = 1; j < str2.size() + 1; j++) {
                int left = dp[i - 1][j] + 1;
                int right = dp[i][j - 1] + 1;
                int chan = dp[i - 1][j - 1];
                if (str1[i-1] != str2[j-1]) {
                    chan ++;
                }
                dp[i][j] = min(min(left, right), chan);
            }
        }

        cout << dp[str1.size()][str2.size()];
    }
}

#转行#
全部评论

相关推荐

06-17 00:26
门头沟学院 Java
程序员小白条:建议换下项目,智能 AI 旅游推荐平台:https://github.com/luoye6/vue3_tourism_frontend 智能 AI 校园二手交易平台:https://github.com/luoye6/vue3_trade_frontend GPT 智能图书馆:https://github.com/luoye6/Vue_BookManageSystem 选项目要选自己能掌握的,然后最好能自己拓展的,分布式这种尽量别去写,不然你只能背八股文了,另外实习的话要多投,尤其是学历不利的情况下,多找几段实习,最好公司title大一点的
无实习如何秋招上岸
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务