class Solution {
public int minDistance(String word1, String word2) {
int m = word1.length() - 1;
int n = word2.length() - 1;
int[][] dp = new int[m + 2][n + 2];
for (int[] d : dp) {
Arrays.fill(d, -1);
}
return helper(word1, word2, m, n, dp);
}
public int helper(String word1, String word2, int m, int n, int[][] dp) {
if (m + 1 == 0 && n + 1 == 0) {
return 0;
}
if (m + 1 == 0 || n + 1 == 0) {
return Math.max(m + 1, n + 1);
}
if (dp[m][n] != -1) return dp[m][n];
if (word1.charAt(m) == word2.charAt(n)) {
dp[m][n] = helper(word1, word2, m - 1, n - 1, dp);
return dp[m][n];
} else {
int delete = 1 + helper(word1, word2, m - 1, n, dp);
int insert = 1 + helper(word1, word2, m, n - 1, dp);
int replace = 1 + helper(word1, word2, m - 1, n - 1, dp);
dp[m][n] = Math.min(Math.min(delete, insert), replace);
return dp[m][n];
}
}
}