-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtrie.cpp
executable file
·60 lines (53 loc) · 1.22 KB
/
trie.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
Data Structure: Trie
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
Space Complexity: O(len • words)
| Operations | Time | Space |
|---------------------|-----------|-------|
| insert(word) | O(len) | O(1) |
| search(word) | O(len) | O(1) |
| starts_with(prefix) | O(len) | O(1) |
*/
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
class TrieNode {
public:
int words;
std::unordered_map<char, TrieNode*> children;
TrieNode() : words(0) {}
};
class Trie {
private:
TrieNode* root;
public:
Trie() : root(new TrieNode()) {}
void insert(const std::string& word) {
TrieNode* node = root;
for (const char& c: word) {
if (!node->children.count(c))
node->children[c] = new TrieNode();
node = node->children[c];
}
node->words++;
}
bool search(const std::string& word) {
TrieNode* node = root;
for (const char& c: word) {
if (!node->children.count(c))
return false;
node = node->children[c];
}
return node->words;
}
bool starts_with(const std::string& prefix) {
TrieNode* node = root;
for (const char& c: prefix) {
if (!node->children.count(c))
return false;
node = node->children[c];
}
return node;
}
};