本题是对前篇博文编辑距离的延伸,比编辑距离
的约束条件更多,但总体处理方法是一致的。
题目名称:最小编辑代价
题目链接:链接
题目描述:
给定两个字符串str1
和str2
,再给定三个整数ic
,dc
和rc
,分别代表插入、删除和替换一个字符的代价,请输出将str1
编辑成str2
的最小代价。
示例1:
输入:
"abc","adc",5,3,2
输出:
2
示例2:
输入:
"abc","adc",5,3,100
输出:
8
备注:
1 <= str1的长度,str2的长度 <= 5000
1 <= ic,dc,rc <= 10000
本题和编辑距离很类似,区别在于编辑距离那道题增加、删除、替换一个字符的代价是相同,本题是可以不同的,但是总体的处理方法是一致的。
参考代码
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) {
int m = str1.length();
int n = str2.length();
int[][] dp = new int[m + 1][n + 1];
// base case: str2 为空串,则需要删除str1子串长度个字符
for (int i = 1; i <= m; i++) {
dp[i][0] = i * dc;
}
// base case: str1为空串,则需要增加str2子串的长度个字符
for (int i = 1; i <= n; i++) {
dp[0][i] = i * ic;
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1];
} else {
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[m][n];
}
}