比较经典的动态规划。 tmp[i][j]代表word1的第i个字符和word2的第j个字符之间的操作数。 针对三种操作,增加,删除和替换,tmp[i][j]的值和tmp[i][j-1],tmp[i-1][j],tmp[i-1][j-1]相关。 要注意的是当word1的第i个字符word1[I-1]和word2的第j个字符word2[j-1]相同时,替换没必要发生,代价为0.
public class Solution {
public int minDistance(String word1, String word2) {
int l1=word1.length();
int l2=word2.length();
if(l1==0)
{
return l2;
}
if(l2==0)
{
return l1;
}
int [][]tmp = new int[l1+1][l2+1];
for( int i=0;i<=l1;i++ )
{
tmp[i][0] = i;
}
for( int j=0;j<=l2;j++ )
{
tmp[0][j] = j;
}
for( int i=1;i<=l1;i++ )
{
for( int j=1;j<=l2;j++ )
{
int temp;
if(word1.charAt(i-1)==word2.charAt(j-1))
{
temp=0;
}
else
{
temp=1;
}
tmp[i][j] = Math.min(tmp[i-1][j]+1,Math.min(tmp[i][j-1]+1,tmp[i-1][j-1]+temp));
}
}
return tmp[l1][l2];
}
}