动态规划解决编辑距离问题,注意dp数组的初始化,dp[i][j]的意义是str1中的i-1子字符串到str2中j-1结尾的字符串的最短编辑距离
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 n1=str1.length();
int n2=str2.length();
char[] s1=str1.toCharArray();
char[] s2=str2.toCharArray();
int[][]dp=new int[n1+1][n2+1];
//dp初始化
dp[0][0]=0;
for(int i=1;i<=n1;i++){
dp[i][0]=i*dc;
}
for(int j=1;j<=n2;j++){
dp[0][j]=j*ic;
}
for(int i=1;i<=n1;i++){
for(int j=1;j<=n2;j++){
if(s1[i-1]==s2[j-1]){
dp[i][j]=dp[i-1][j-1];
}
else{
int removeCost=dp[i-1][j]+dc;
int insertCost=dp[i][j-1]+ic;
int replaceCost=dp[i-1][j-1]+rc;
int totalConst=Math.min(replaceCost,removeCost);
dp[i][j]=Math.min(totalConst,insertCost);
}
}
}
return dp[n1][n2];
}
}