这是动态规划策略中的levenshtien算法。在我的代码中当str1想要转换为str2时必须更改。插入1 char有2个成本并删除1个char成本1.代码示例必须打印2但打印1.why?感谢您的帮助。
public class Distance {
static int min(int x,int y)
{
if (x < y ) return x;
else return y;
}
static int editDistDP(String str1, String str2, int m, int n)
{
int dp[][] = new int[m+1][n+1];
for (int i=0; i<=m; i++)
{
for (int j=0; j<=n; j++)
{
if (i==0)
dp[i][j] = j; // Min. operations = j
else if (j==0)
dp[i][j] = i; // Min. operations = i
else if (str1.charAt(i-1) == str2.charAt(j-1))
dp[i][j] = dp[i-1][j-1];
else
dp[i][j] = min(dp[i][j-1] + 2, // Insert
dp[i-1][j] + 1); // Remove
}
}
return dp[m][n];
}
public static void main(String args[])
{
String str1 = "pple";
String str2 = "apple";
System.out.println( editDistDP( str1 , str2 , str1.length(), str2.length()) );
}
}