We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent cdaa42e commit 3edbdb9Copy full SHA for 3edbdb9
kotlin/0072-edit-distance.kt
@@ -1,3 +1,6 @@
1
+/*
2
+* DP Time O(m*n) and space O(m*n)
3
+*/
4
class Solution {
5
fun minDistance(word1: String, word2: String): Int {
6
@@ -23,7 +26,37 @@ class Solution {
23
26
}
24
27
25
28
-
29
+
30
return cache[0][0]
31
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
+}
0 commit comments