-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplement_Trie_(Prefix Tree).cpp
More file actions
79 lines (74 loc) · 2.04 KB
/
Implement_Trie_(Prefix Tree).cpp
File metadata and controls
79 lines (74 loc) · 2.04 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
78
79
# number : 208
const int MAX_SIZE = 26;
class Trie {
public:
struct TrieNode {
bool isEnd;
int num;
TrieNode *children[MAX_SIZE];
TrieNode()
{
num = 0;
isEnd = false;
for (int i = 0; i < MAX_SIZE; i++)
children[i] = NULL;
}
};
/** Initialize your data structure here. */
Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
void insert(string word) {
int length = word.size();
if (length == 0) { return; }
TrieNode *p = root;
for (int i = 0; i < length; i++)
{
int index = word[i] - 'a';
if (p->children[index] == NULL)
{
TrieNode* pNode = new TrieNode();
p->children[index] = pNode;
p->num++;
}
p = p->children[index];
}
p->isEnd = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
int length = word.size();
if (length == 0) { return false; }
TrieNode *p = root;
for (int i = 0; i < length; i++)
{
int index = word[i] - 'a';
if (p->children[index] == NULL) { return false; }
p = p->children[index];
}
return p->isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
int length = prefix.size();
if (length == 0) { return false; }
TrieNode *p = root;
for (int i = 0; i < length; i++)
{
int index = prefix[i] - 'a';
if (p->children[index] == NULL) { return false; }
p = p->children[index];
}
return true;
}
private:
TrieNode *root;
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/