Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character
分析:看到最优化问题先想动规,找到子问题和状体转移方程,那么这个问题就可以用动规解决。
子问题:从word1的前i个字符转移到word2的前j个字符需要的最小步数,用dp[i][j]表示,那么最后答案就是dp[len1][len2].
状态转移方程:
因为有三种转移方式,replace, insert, delete,
如果i,j位置上字符相同,则不需要操作,dp[i+1][j+1] = dp[i][j];
如果不相同,则有三种转移方式:
replace = dp[i][j] + 1;
insert = dp[i][j+1] + 1;
delete = dp[i+1][j] + 1;
dp[i+1][j+1] = min{ replace, insert, delete }.
public class Solution {
public int minDistance(String word1, String word2) {
//检查参数
if(word1==null || word2==null)
return -1;
int len1 = word1.length();
int len2 = word2.length();
//转移矩阵记录从word1前i个字符到word2前j个字符转换所需要的步数
int[][] dp = new int[len1+1][len2+1];
for(int i=0; i<=len1; i++)
dp[i][0] = i;
for(int j=0; j<=len2; j++)
dp[0][j] = j;
for(int i=0; i<len1; i++){
char c1 = word1.charAt(i);
for(int j=0; j<len2; j++){
char c2 = word2.charAt(j);
if(c1 == c2)
dp[i+1][j+1] = dp[i][j];
else{
int replace = dp[i][j]+1;
int insert = dp[i][j+1]+1;
int delete = dp[i+1][j]+1;
//find the min one
int min = Math.min(replace, insert);
min = Math.min(min, delete);
dp[i+1][j+1] = min;
}
}
}
return dp[len1][len2];
}
}