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
c) Replace a character
思路:双序列型动态规划,找最后一步,从两个尾巴开始看起,注意所有的操作都是作用于s1. 目标是把s1 变成s2,所以分别是insert,delete,replace将问题缩小一步,变成子问题;
f[i][j]表示,s1[i] 变换到s2[j]所需要的最小edit distance;
状态转移方程: if s1[i-1] == s2[j-1] : f[i][j] = f[i-1][j-1]
if s1[i-1] != s2[j-1] : f[i][j] = Math.min( (insert) f[i][j-1] +1 , (delete) f[i-1][j] + 1, (replace) f[i-1][j-1] +1 ) ;
注意初始化[0][0] 还有第一行和第一列;
class Solution {
public int minDistance(String word1, String word2) {
int m = word1.length();
int n = word2.length();
int[][] dp = new int[m + 1][n + 1];
// 1st row;
for(int j = 0; j <= n; j++) {
dp[0][j] = j;
}
// 1st col;
for(int i = 0; i <= m; i++) {
dp[i][0] = i;
}
// calculate matrix;
for(int i = 1; i <= m; i++) {
for(int j = 1; j <= n; j++) {
if(word1.charAt(i - 1) == word2.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] =Math.min(dp[i][j - 1] + 1, Math.min(dp[i - 1][j] + 1, dp[i - 1][j - 1] + 1));
}
}
}
return dp[m][n];
}
}
这题转移方程只与前i和i-1 row有关系,所以可以通过滚动数组降维成1维;用两个row就可以实现,注意:这个时候,initial的方程只能写在两个for循环里面,因为边循环边计算下两行的,如果写在外面分别进行initial col,那样会出错;
class Solution {
public int minDistance(String word1, String word2) {
int m = word1.length();
int n = word2.length();
int[][] dp = new int[2][n + 1];
for(int i = 0; i <= m; i++) {
for(int j = 0; j <= n; j++) {
if(i == 0) {
dp[i % 2][j] = j;
} else if(j == 0) {
dp[i % 2][j] = i;
} else {
if(word1.charAt(i - 1) == word2.charAt(j - 1)) {
dp[i % 2][j] = dp[(i - 1) % 2][j - 1];
} else {
dp[i % 2][j] = Math.min(dp[(i - 1) % 2][j - 1], Math.min(dp[(i - 1) % 2][j], dp[i % 2][j - 1])) + 1;
}
}
}
}
return dp[m % 2][n];
}
}