NC35 最小编辑代价

思路

当i字符等于j字符时:dp[i][j] = dp[i-1][j-1]
当i字符不等于j字符时:dp[i][j] = min(insert, delete, replace)
int insert = dp[i][j-1] + 1; i个编辑成j-1个字符,再插入
int delete = dp[i-1][j] + 1; i-1个编辑成j个字母,再删除
int replace = dp[i-1][j-1] + 1; i-1个编辑成j-1个字母,再替换

代码

class Solution {
public:
    /**
     * min edit cost
     * @param str1 string字符串 the string
     * @param str2 string字符串 the string
     * @param ic int整型 insert cost
     * @param dc int整型 delete cost
     * @param rc int整型 replace cost
     * @return int整型
     */
    static const int maxn = 5e3 + 10;
    int dp[maxn][maxn];
    int minEditCost(string str1, string str2, int ic, int dc, int rc) {
        // write code here
        int n = str1.size(), m = str2.size();
        memset(dp, 0x3f3f3f3f, sizeof(dp));
        for(int i = 0; i <= n; i++){
            dp[i][0] = dc * i;
        }
        for(int i = 0; i <= m; i++){
            dp[0][i] = ic * i;
        }
        for(int i = 1; i <= n; i++){
            for(int j = 1; j <= m; j++){
                if(str1[i - 1] != str2[j - 1]){
                    int x, y, z;
                    x = dp[i][j - 1] + ic;//str1插入
                    y = dp[i - 1][j] + dc;//str1删除
                    z = dp[i - 1][j - 1] + rc;//str1替换
                    dp[i][j] = min(min(x, y), z);
                }else{
                    dp[i][j] = dp[i - 1][j - 1];
                }
            }
        }
        return dp[str1.size() - 1][str2.size() - 1];
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值