퉀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
¶¯Ì¬¹æ»®¾µäÌâÄ¿£¬ÕÒµ½µÝÍÆ¹ØÏµ£¬³õʼ»¯£¬È»ºóµÝÍÆ¡£
ÕâÀïµÄdp[i][j]±íʾword1.substring(0, i+1)ºÍword2.substring(0, j+1)µÄ×îС±à¼¾àÀë¡£
´úÂë
public class EditDistance {
public int minDistance(String word1, String word2) {
char[] word1CharArray = word1.toCharArray();
char[] word2CharArray = word2.toCharArray();
int M = word1CharArray.length;
int N = word2CharArray.length;
if (M == 0 || N == 0) {
return M + N;
}
int[][] dp = new int[M][N];
// init
dp[0][0] = word1CharArray[0] == word2CharArray[0] 0 : 1;
for (int i = 1; i < M; ++i) {
dp[i][0] = word1CharArray[i] == word2CharArray[0] i
: dp[i - 1][0] + 1;
}
for (int j = 1; j < N; ++j) {
dp[0][j] = word1CharArray[0] == word2CharArray[j] j
: dp[0][j - 1] + 1;
}
// dp
for (int i = 1; i < M; ++i) {
for (int j = 1; j < N; ++j) {
if (word1CharArray[i] == word2CharArray[j]) {
dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + 1;
dp[i][j] = Math.min(dp[i][j], dp[i - 1][j - 1]);
} else {
dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]);
dp[i][j] = Math.min(dp[i][j], dp[i - 1][j - 1]) + 1;
}
}
}
return dp[M - 1][N - 1];
}
}