题解 | #NC35 最小编辑代价#

最小编辑代价

http://www.nowcoder.com/practice/05fed41805ae4394ab6607d0d745c8e4

与力扣 72. 编辑距离 类似

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[][] dp = new int[str1.length() + 1][str2.length() + 1];
        // str1 ==> str2(str2 不能修改)
        //第一列代表将 str1 全部删除
        for (int i = 0; i < dp.length; i++) dp[i][0] = i * dc;
        //第一行代表 不断添加字符到 str1,直到和 str2 相同
        for (int i = 0; i < dp[0].length; i++) dp[0][i] = i * ic;
        for (int i = 1; i < dp.length; i++) {
            for (int j = 1; j < dp[0].length; j++) {
                if (str1.charAt(i - 1) == str2.charAt(j - 1)) 
                    dp[i][j] = dp[i - 1][j - 1];
                else {
                    //替换
                    int replace = dp[i - 1][j - 1] + rc;
                    //按行走要删
                    int delete = dp[i - 1][j] + dc;
                    //按列要加
                    int insert = dp[i][j - 1] + ic;
                    //取最小
                    dp[i][j] = Math.min(replace, Math.min(delete, insert));
                }
            }
        }
        return dp[str1.length()][str2.length()];
    }
}
全部评论

相关推荐

03-04 07:14
门头沟学院 C++
后测速成辅导一两个月...:老板:都给工作机会了还想要工资,哪来这么多好事
点赞 评论 收藏
分享
老板加个卤鸡蛋:HR看了以为来卧底来了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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