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

计算字符串的编辑距离

https://www.nowcoder.com/practice/3959837097c7413a961a135d7104c314

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

int main() {
    string str1, str2;
    cin >> str1 >> str2;
    int ans = 0;
    if(str1.length() == 0 || str2.length() == 0) ans = ans + str1.length() + str2.length();
    else{
        vector<vector<int>> dp(str1.length()+1, vector<int>(str2.length()+1, 0));
        for(int i = 1; i <= str1.length(); i++) dp[i][0] = i;
        for(int j = 1; j <= str2.length(); j++) dp[0][j] = j;
        for(int i = 1; i <= str1.length(); i++){
            for(int j = 1; j <= str2.length(); j++){
                dp[i][j] = min(min(dp[i-1][j] + 1, dp[i][j-1] + 1), dp[i-1][j-1] + (str1[i-1] != str2[j-1]));
            }
        }
        ans = dp[str1.length()][str2.length()];
    }
      
    cout << ans << endl;
    return 0;
}

全部评论

相关推荐

2025-12-25 16:26
已编辑
河北科技学院 Java
勇敢的牛油不服输:2800-300那不等于2500一个月吗兄弟们
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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