最小编辑代价
题目描述
给定两个字符串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];
}
}