File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ Definition of a TrieNode:
3
+
4
+ data class TrieNode(
5
+ var isWord: Boolean = false,
6
+ val children: HashMap<Char, TrieNode> = hashMapOf()
7
+ )
8
+ */
9
+
10
+ class InsertAndSearchWordsWithWildcards {
11
+ private val root = TrieNode ()
12
+
13
+ fun insert (word : String ) {
14
+ var node = root
15
+ for (c in word) {
16
+ if (c !in node.children) {
17
+ node.children[c] = TrieNode ()
18
+ }
19
+ node = node.children[c]!!
20
+ }
21
+ node.isWord = true
22
+ }
23
+
24
+ fun search (word : String ): Boolean {
25
+ // Start searching from the root of the trie.
26
+ return searchHelper(0 , word, root)
27
+ }
28
+
29
+ fun searchHelper (wordIndex : Int , word : String , node : TrieNode ): Boolean {
30
+ var node = node
31
+ for (i in wordIndex until word.length) {
32
+ val c = word[i]
33
+ if (c == ' .' ) {
34
+ for (child in node.children.values) {
35
+ // If a match is found, return true.
36
+ if (searchHelper(i + 1 , word, child)) {
37
+ return true
38
+ }
39
+ }
40
+ } else if (c in node.children) {
41
+ node = node.children[c]!!
42
+ } else {
43
+ return false
44
+ }
45
+ // After processing the last character, return true if we've
46
+ // reached the end of a word.
47
+ }
48
+ return node.isWord
49
+ }
50
+ }
You can’t perform that action at this time.
0 commit comments