File tree Expand file tree Collapse file tree 1 file changed +66
-0
lines changed Expand file tree Collapse file tree 1 file changed +66
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time: O(n), per operation
2
+ // Space: O(1)
3
+
4
+ class TrieNode {
5
+ public:
6
+ // Initialize your data structure here.
7
+ TrieNode () : is_string(false ) {
8
+
9
+ }
10
+ bool is_string;
11
+ unordered_map<char , TrieNode *> leaves;
12
+ };
13
+
14
+ class Trie {
15
+ public:
16
+ Trie () {
17
+ root_ = new TrieNode ();
18
+ }
19
+
20
+ // Inserts a word into the trie.
21
+ void insert (string word) {
22
+ auto *cur = root_;
23
+ for (const auto & c : word) {
24
+ if (!cur->leaves .count (c)) {
25
+ cur->leaves [c] = new TrieNode ();
26
+ }
27
+ cur = cur->leaves [c];
28
+ }
29
+ cur->is_string = true ;
30
+ }
31
+
32
+ // Returns if the word is in the trie.
33
+ bool search (string word) {
34
+ auto *node = childSearch (word);
35
+ if (node) {
36
+ return node->is_string ;
37
+ }
38
+ return false ;
39
+ }
40
+
41
+ // Returns if there is any word in the trie
42
+ // that starts with the given prefix.
43
+ bool startsWith (string prefix) {
44
+ return childSearch (prefix);
45
+ }
46
+
47
+ TrieNode * childSearch (const string& word) {
48
+ auto *cur = root_;
49
+ for (const auto & c : word) {
50
+ if (cur->leaves .count (c)) {
51
+ cur = cur->leaves [c];
52
+ } else {
53
+ return nullptr ;
54
+ }
55
+ }
56
+ return cur;
57
+ }
58
+
59
+ private:
60
+ TrieNode* root_;
61
+ };
62
+
63
+ // Your Trie object will be instantiated and called as such:
64
+ // Trie trie;
65
+ // trie.insert("somestring");
66
+ // trie.search("key");
You can’t perform that action at this time.
0 commit comments