Skip to content

Commit 1954c88

Browse files
committed
Insert And Search Words With Wildcards
1 parent 03f3a4c commit 1954c88

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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+
}

0 commit comments

Comments
 (0)