-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathTrie.cpp
54 lines (41 loc) · 913 Bytes
/
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
#include "Trie.h"
TrieNode *getNode(char key,std::string value)
{
TrieNode *pNode = new TrieNode;
pNode->key = key;
pNode->value = value;
pNode->isEndWord = false;
for (int i = 0; i < ALPHABET_SIZE; i++)
pNode->children[i] = NULL;
return pNode;
}
Trie::Trie()
{
}
void Trie::Insert(string key)
{
struct TrieNode *pCrawl = rootNode;
std::string k = "";
for (int i = 0; i < key.length(); i++)
{
int index = key[i] - 'a';
k += key[i];
if (!pCrawl->children[index])
pCrawl->children[index] = getNode(key[i],k);
pCrawl = pCrawl->children[index];
}
// mark last node as leaf
pCrawl->isEndWord = true;
}
bool Trie::Search(string key)
{
struct TrieNode *pCrawl = rootNode;
for (int i = 0; i < key.length(); i++)
{
int index = key[i] - 'a';
if (!pCrawl->children[index])
return false;
pCrawl = pCrawl->children[index];
}
return (pCrawl != NULL && pCrawl->isEndWord);
}