forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0072-edit-distance.java
43 lines (39 loc) · 1.38 KB
/
0072-edit-distance.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
//Refer to neetcode's video
//Memoized code
classSolution {
publicintminDistance(Stringword1, Stringword2) {
intm = word1.length() - 1;
intn = word2.length() - 1;
int[][] dp = newint[m + 2][n + 2];
for (int[] d : dp) {
Arrays.fill(d, -1);
}
returnhelper(word1, word2, m, n, dp);
}
publicinthelper(Stringword1, Stringword2, intm, intn, int[][] dp) {
//the strings are null
if (m + 1 == 0 && n + 1 == 0) {
return0;
}
//one of the strings are null
if (m + 1 == 0 || n + 1 == 0) {
returnMath.max(m + 1, n + 1);
}
//both values at the index are equal
if (dp[m][n] != -1) returndp[m][n];
if (word1.charAt(m) == word2.charAt(n)) {
dp[m][n] = helper(word1, word2, m - 1, n - 1, dp);
returndp[m][n];
} else {
//try deletion
intdelete = 1 + helper(word1, word2, m - 1, n, dp);
//try insertion
intinsert = 1 + helper(word1, word2, m, n - 1, dp);
//try replacing
intreplace = 1 + helper(word1, word2, m - 1, n - 1, dp);
//now we'll choose the minimum out of these 3 and add 1 for the operation cost
dp[m][n] = Math.min(Math.min(delete, insert), replace);
returndp[m][n];
}
}
}