最小编辑代价

最小编辑代价

题目描述

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

代码

import java.util.*;


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 l1 = str1.length();
        int l2 = str2.length();
        char[] cs1 = str1.toCharArray();
        char[] cs2 = str2.toCharArray();
        int[][] dp = new int[l1+1][l2+1];
        dp[0][0] = 0;
        //空串编辑为str2的代价
        for(int j=1; j<l2+1; j++)
            dp[0][j] = ic*j;
        //str1编辑成空串的代价
        for(int i=1; i<l1+1; i++)
            dp[i][0] = dc*i;
        //动态规划
        //当前1-i的字符编辑成1-j的代价
        for(int i=1; i<l1+1; i++){
            for(int j=1; j<l2+1; j++){
                if(cs1[i-1]==cs2[j-1]){
                    dp[i][j] = dp[i-1][j-1];
                }else{
                    //dp[i][j-1]表示str1:0-i编辑成str2:0-j-1的代价,
                    //          那么str1:0-i编辑成str2:0-j的代价可以是:
                    //          插入的代价dp[i][j-1] + ic
                    //dp[i-1][j]表示str1:0-i-1编辑成str2:0-j的代价,
                    //          那么str1:0-i编辑成str2:0-j的代价可以是:
                    //          删除的代价dp[i-1][j] + ic,寻找i-1编辑成j的代价加上删除的代价
                    dp[i][j] = Math.min( 
                               Math.min(dp[i][j-1]+ic, dp[i-1][j]+dc),
                               dp[i-1][j-1]+rc
                    );
                }
            }
        }
        return dp[l1][l2];
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值