forked from Cyberavater/leetcode_practice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
211. Design Add and Search Words Data Structure.kt
48 lines (40 loc) · 1.19 KB
/
211. Design Add and Search Words Data Structure.kt
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
48
class Trie {
val children = hashMapOf<Char, Trie>()
var tail = false
}
class WordDictionary() {
private val trie = Trie()
fun addWord(word: String) {
var cur = trie
for (letter in word) {
if (letter !in cur.children) {
cur.children[letter] = Trie()
}
cur = cur.children[letter]!!
}
cur.tail = true
}
fun search(word: String): Boolean {
fun dfs(startingIndex: Int, node: Trie): Boolean {
var cur = node
for (letterIndex in startingIndex until word.length) {
val letter = word[letterIndex]
if (letter == '.') {
for (child in cur.children.values) {
if (dfs(letterIndex + 1, child)) {
return true
}
}
return false
} else {
if (letter !in cur.children) {
return false
}
cur = cur.children[letter]!!
}
}
return cur.tail
}
return dfs(0, trie)
}
}