题解 | #编辑距离(二)#

编辑距离(二)

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

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 len1 = str1.length(); // 获取 str1 的长度
        int len2 = str2.length(); // 获取 str2 的长度
        int[][] dp = new int[len1 + 1][len2 + 1];
        
        // 别忘了进行初始化
        for (int i = 0; i <= len1; i++) {
            dp[i][0] = i * dc;
        }
        for (int j = 0; j <= len2; j++) {
            dp[0][j] = j * ic;
        }
        
        for (int i = 1; i <= len1; i++) {
            for (int j = 1; j <= len2; j++) {
                // 如果在当前位置上,str1 和 str2 的字符相等,那么不需要进行任何操作,dp[i][j] = dp[i - 1][j - 1]
                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, Math.min(dp[i - 1][j] + dc, dp[i][j - 1] + ic));
                }
            }
        }
        return dp[len1][len2];
    }
}
全部评论

相关推荐

昨天 11:15
中南大学 Java
好可爱的hr姐姐哈哈哈哈
黑皮白袜臭脚体育生:兄弟们貂蝉在一起,吕布开了
点赞 评论 收藏
分享
07-08 13:48
门头沟学院 C++
点赞 评论 收藏
分享
半解316:内容充实,细节需要修改一下。 1,整体压缩为一页。所有内容顶格。 2,项目描述删除,直接写个人工作量 修改完之后还需要建议,可以私聊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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