Skip to content

Commit 3edbdb9

Browse files
authored
Update 0072-edit-distance.kt
1 parent cdaa42e commit 3edbdb9

File tree

1 file changed

+34
-1
lines changed

1 file changed

+34
-1
lines changed

Diff for: kotlin/0072-edit-distance.kt

+34-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
/*
2+
* DP Time O(m*n) and space O(m*n)
3+
*/
14
class Solution {
25
fun minDistance(word1: String, word2: String): Int {
36

@@ -23,7 +26,37 @@ class Solution {
2326
}
2427
}
2528
}
26-
29+
2730
return cache[0][0]
2831
}
2932
}
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

Comments
 (0)