-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy path2707-extra-characters-in-a-string.kt
More file actions
47 lines (37 loc) · 1.16 KB
/
2707-extra-characters-in-a-string.kt
File metadata and controls
47 lines (37 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Solution {
private lateinit var memo: IntArray
private class TrieNode {
val children = HashMap<Char, TrieNode>()
var isWord = false
}
fun minExtraChar(s: String, dictionary: Array<String>): Int {
val root = buildTrie(dictionary)
memo = IntArray(s.length) { -1 }
return dfs(0, s, root)
}
private fun dfs(index: Int, s: String, root: TrieNode): Int {
if (index == s.length) return 0
if (memo[index] != -1) return memo[index]
var result = 1 + dfs(index + 1, s, root)
var node = root
for (i in index until s.length) {
node = node.children[s[i]] ?: break
if (node.isWord) {
result = minOf(result, dfs(i + 1, s, root))
}
}
memo[index] = result
return result
}
private fun buildTrie(dictionary: Array<String>): TrieNode {
val root = TrieNode()
for (word in dictionary) {
var node = root
for (ch in word) {
node = node.children.getOrPut(ch) { TrieNode() }
}
node.isWord = true
}
return root
}
}