Skip to content

Commit 0a6b00f

Browse files
authored
Create 0072-edit-distance.kt
1 parent 11c09b0 commit 0a6b00f

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

kotlin/0072-edit-distance.kt

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
fun minDistance(word1: String, word2: String): Int {
3+
4+
val cache = Array(word1.length + 1) {
5+
IntArray(word2.length + 1){ Integer.MAX_VALUE }
6+
}
7+
8+
for(j in 0..word2.length)
9+
cache[word1.length][j] = word2.length - j
10+
for(i in 0..word1.length)
11+
cache[i][word2.length] = word1.length - i
12+
13+
for(i in word1.lastIndex downTo 0) {
14+
for(j in word2.lastIndex downTo 0) {
15+
if(word1[i] == word2[j]) {
16+
cache[i][j] = cache[i + 1][j + 1]
17+
}else {
18+
cache[i][j] = 1 + minOf(
19+
cache[i + 1][j],
20+
cache[i][j + 1],
21+
cache[i + 1][j + 1]
22+
)
23+
}
24+
}
25+
}
26+
27+
return cache[0][0]
28+
}
29+
}

0 commit comments

Comments
 (0)