really classic DP:
Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2.
You have the following three operations permitted on a word:
Insert a character
Delete a character
Replace a character
remember, we need to convert word1 to word2
class Solution {
public int minDistance(String word1, String word2) {
if (word1 == null || word2 == null) return 0;
int m = word1.length();
int n = word2.length();
int[][] dp = new int[m+1][n+1];
dp[0][0] = 0;
for (int i = 1; i <= m; i++) {
dp[i][0] = i;
}
for (int i = 1; i <= n; i++) {
dp[0][i] = i;
}
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(Math.min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]) + 1; //delete(i-1), insert(j-1), replace(i-1,j-1)
}
}
}
return dp[m][n];
}
}