-
Notifications
You must be signed in to change notification settings - Fork 102
Expand file tree
/
Copy pathTrie.cpp
More file actions
78 lines (63 loc) · 1.7 KB
/
Trie.cpp
File metadata and controls
78 lines (63 loc) · 1.7 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// Implementation of Trie data structure in C++.
/*
* Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_0 = obj->search(word);
* bool param_0 = obj->startsWith(word);
*/
#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;
// Create Trie node
class TrieNode {
public:
char val;
unordered_map<char, TrieNode*> children;
bool is_end;
// Constructor
TrieNode(char val = '\0', bool is_end = false) : val(val), is_end(is_end) {}
};
class Trie {
private:
TrieNode* root;
public:
// Create root node
Trie() {
root = new TrieNode();
}
// Insert a word into the Trie
void insert(const string& word) {
TrieNode* node = root;
for (char c : word) {
if (node->children.find(c) == node->children.end()) {
node->children[c] = new TrieNode(c);
}
node = node->children[c];
}
node->is_end = true; // Mark the end of a word
}
// Search for a word in the Trie
bool search(const string& word) {
TrieNode* node = root;
for (char c : word) {
if (node->children.find(c) == node->children.end()) {
return false;
}
node = node->children[c];
}
return node->is_end;
}
// Check if a word in Trie starts with prefix
bool startsWith(const string& prefix) {
TrieNode* node = root;
for (char c : prefix) {
if (node->children.find(c) == node->children.end()) {
return false;
}
node = node->children[c];
}
return true;
}
};