forked from MAYANK25402/Hactober-2023-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrie.cpp
44 lines (37 loc) · 1.02 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
#include <unordered_map>
#include <iostream>
struct TrieNode {
std::unordered_map<char, TrieNode*> children;
bool is_end_of_word;
TrieNode() : is_end_of_word(false) {}
};
class Trie {
public:
TrieNode* root;
Trie() { root = new TrieNode(); }
void insert(std::string word) {
TrieNode* node = root;
for(char ch : word) {
if(!node->children.count(ch))
node->children[ch] = new TrieNode();
node = node->children[ch];
}
node->is_end_of_word = true;
}
bool search(std::string word) {
TrieNode* node = root;
for(char ch : word) {
if(!node->children.count(ch))
return false;
node = node->children[ch];
}
return node && node->is_end_of_word;
}
};
int main() {
Trie trie;
trie.insert("hello");
std::cout << trie.search("hello") << std::endl; // Output: 1
std::cout << trie.search("hell") << std::endl; // Output: 0
return 0;
}