File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed
design-add-and-search-words-data-structure Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments