Skip to content

Commit 45f9d49

Browse files
committed
Add design add and search words data structure solution
1 parent 791de24 commit 45f9d49

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
class WordDictionary() {
2+
3+
class TrieNode {
4+
val children = mutableMapOf<Char, TrieNode>()
5+
var isEndOfWord = false
6+
}
7+
8+
private val root = TrieNode()
9+
10+
fun addWord(word: String) {
11+
var current = root
12+
13+
for (char in word) {
14+
if (char !in current.children) {
15+
current.children[char] = TrieNode()
16+
}
17+
current = current.children[char]!!
18+
}
19+
20+
current.isEndOfWord = true
21+
}
22+
23+
fun search(word: String): Boolean {
24+
return searchHelper(word, 0, root)
25+
}
26+
27+
private fun searchHelper(word: String, index: Int, node: TrieNode): Boolean {
28+
if (index == word.length) {
29+
return node.isEndOfWord
30+
}
31+
32+
val char = word[index]
33+
34+
return if (char == '.') {
35+
for (child in node.children.values) {
36+
if (searchHelper(word, index + 1, child)) {
37+
return true
38+
}
39+
}
40+
false
41+
} else {
42+
val child = node.children[char] ?: return false
43+
searchHelper(word, index + 1, child)
44+
}
45+
}
46+
}

0 commit comments

Comments
 (0)