-
Notifications
You must be signed in to change notification settings - Fork 0
/
trie_str.h
53 lines (41 loc) · 936 Bytes
/
trie_str.h
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
#include <string>
const size_t ALPHABET_SIZE = 26; //for english words
struct TrieNode
{
bool isEndOfWord;
TrieNode *children[ALPHABET_SIZE];
TrieNode():
isEndOfWord(false)
{
for (size_t i = 0; i < ALPHABET_SIZE; ++i)
children[i] = nullptr;
}
~TrieNode()
{
//TODO: clean allocated memory
}
void insert(const std::string& key)
{
TrieNode* iterator = this;
for (size_t i = 0; i < key.length(); ++i)
{
size_t index = key[i] - 'a';
if (!iterator->children[index])
iterator->children[index] = new TrieNode;
iterator = iterator->children[index];
}
iterator->isEndOfWord = true;
}
bool search(const std::string& key)
{
TrieNode* current = this;
for (size_t i = 0; i < key.length(); ++i)
{
size_t index = key[i] - 'a';
if (!current->children[index])
return false;
current = current->children[index];
}
return (current != nullptr && current->isEndOfWord);
}
};