File tree Expand file tree Collapse file tree 1 file changed +34
-1
lines changed Expand file tree Collapse file tree 1 file changed +34
-1
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ * DP Time O(m*n) and space O(m*n)
3
+ */
1
4
class Solution {
2
5
fun minDistance (word1 : String , word2 : String ): Int {
3
6
@@ -23,7 +26,37 @@ class Solution {
23
26
}
24
27
}
25
28
}
26
-
29
+
27
30
return cache[0 ][0 ]
28
31
}
29
32
}
33
+
34
+ /*
35
+ * DP Time O(m*n) and optimized space O(n)
36
+ */
37
+ class Solution {
38
+ fun minDistance (word1 : String , word2 : String ): Int {
39
+ val m = word1.length
40
+ val n = word2.length
41
+ var prev = IntArray (n + 1 ) { it }
42
+
43
+ for (i in 1 .. m) {
44
+ val new = IntArray (n + 1 )
45
+ new[0 ] = i
46
+ for (j in 1 .. n) {
47
+ if (word1[i - 1 ] == word2[j - 1 ]) {
48
+ new[j] = prev[j - 1 ]
49
+ } else {
50
+ new[j] = 1 + minOf(
51
+ prev[j],
52
+ prev[j - 1 ],
53
+ new[j - 1 ]
54
+ )
55
+ }
56
+ }
57
+ prev = new
58
+ }
59
+
60
+ return prev[n]
61
+ }
62
+ }
You can’t perform that action at this time.
0 commit comments