MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / Trie

Class Trie

kotlin/Tries/DesignATrie.kt:6–50  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

4)
5
6class Trie {
7 val root = TrieNode()
8
9 fun insert(word: String) {
10 var node = root
11 for (c in word.toCharArray()) {
12 // For each character in the word, if it's not a child of
13 // the current node, create a new TrieNode for that
14 // character.
15 if (c !in node.children) {
16 node.children[c] = TrieNode()
17 }
18 node = node.children[c]!!
19 }
20 // Mark the last node as the end of a word.
21 node.isWord = true
22 }
23
24 fun search(word: String): Boolean {
25 var node = root
26 for (c in word.toCharArray()) {
27 // For each character in the word, if it's not a child of
28 // the current node, the word doesn't exist in the Trie.
29 if (c !in node.children) {
30 return false
31 }
32 node = node.children[c]!!
33 }
34 // Return whether the current node is marked as the end of the word.
35 return node.isWord
36 }
37
38 fun hasPrefix(prefix: String): Boolean {
39 var node = root
40 for (c in prefix.toCharArray()) {
41 if (c !in node.children) {
42 return false
43 }
44 node = node.children[c]!!
45 }
46 // Once we've traversed the nodes corresponding to each
47 // character in the prefix, return True.
48 return true
49 }
50}

Callers

nothing calls this directly

Calls 1

TrieNodeClass · 0.70

Tested by

no test coverage detected