NC35 编辑距离(二)

描述

给定两个字符串str1和str2,再给定三个整数ic,dc和rc,分别代表插入、删除和替换一个字符的代价,请输出将str1编辑成str2的最小代价。

题解:利用动态规划的思想,dp[i][j]为将str1[0:i-1]处理成str2[0:j-1]的意思

str1[i]==str2[j]时,dp[i][j]=dp[i-1][j-1]+rc

str1[i]!=str2[j]时,dp[i][j]=dp[i-1][j]+dc或dp[i][j]=dp[i][j-1]+ic

取其中最小值作为转移代价。

public class Solution {
    /**
     * 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整型
     */
    public int minEditCost (String str1, String str2, int ic, int dc, int rc) {
        // write code here
        int len1=str1.length();
        int len2=str2.length();
        
        int[][] dp=new int[len1+1][len2+1];
        
        dp[0][0]=0;
        
        for(int i=1;i<=len1;i++)
        {
            dp[i][0]=dc*i;
        }
        
        for(int j=1;j<=len2;j++)
        {
            dp[0][j]=ic*j;
        }
        
        for(int i=1;i<=len1;i++)
        {
            for(int j=1;j<=len2;j++)
            {
                if(str1.charAt(i-1)==str2.charAt(j-1))
                {
                    dp[i][j]=dp[i-1][j-1];
                }
                else{
                    dp[i][j]=Math.min(dp[i-1][j-1]+rc,dp[i-1][j]+dc);
                    dp[i][j]=Math.min(dp[i][j],dp[i][j-1]+ic);
                }
            }
        }
        return dp[len1][len2];
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值