Skip to content

Commit 17220e8

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

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

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

+33
Original file line numberDiff line numberDiff line change
@@ -60,3 +60,36 @@ class Solution {
6060
return prev[n]
6161
}
6262
}
63+
64+
65+
/*
66+
* DFS/Recursion + memoization Time O(m*n) and space O(n*m)
67+
*/
68+
class Solution {
69+
fun minDistance(word1: String, word2: String): Int {
70+
71+
val cache = Array(word1.length + 1) { IntArray(word2.length + 1){ Integer.MAX_VALUE } }
72+
73+
fun dfs(i: Int, j: Int): Int {
74+
if (i == word1.length && j == word2.length) return 0
75+
else if (i == word1.length) return word2.length - j
76+
else if (j == word2.length) return word1.length - i
77+
78+
if (cache[i][j] != Integer.MAX_VALUE) return cache[i][j]
79+
80+
if (word1[i] == word2[j]) {
81+
cache[i][j] = dfs(i + 1, j + 1)
82+
} else {
83+
cache[i][j] = 1 + minOf(
84+
dfs(i + 1, j),
85+
dfs(i, j + 1),
86+
dfs(i + 1, j + 1)
87+
)
88+
}
89+
90+
return cache[i][j]
91+
}
92+
93+
return dfs(0, 0)
94+
}
95+
}

0 commit comments

Comments
 (0)