-
Notifications
You must be signed in to change notification settings - Fork 0
/
trie.cpp
61 lines (53 loc) · 1.53 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <fstream>
#include <string>
#include "./utils.cpp"
using std::ifstream;
using std::string;
#define CHAR_SIZE 128
class TrieNode{
public:
TrieNode *children[CHAR_SIZE];
bool leaf;
TrieNode *getNode(){
TrieNode *newNode = new TrieNode;
newNode->leaf = false;
for (int i = 0; i < CHAR_SIZE; i++)
newNode->children[i] = nullptr;
return newNode;
}
};
class Trie{
private:
TrieNode tr;
TrieNode *root = new TrieNode();
void insert(string str, TrieNode *root){
for (int i = 0; i < str.length(); i++){
if (root->children[str[i]] == nullptr)
root->children[str[i]] = root->getNode();
root = root->children[str[i]];
}
root->leaf = true;
}
public:
bool search(string str, TrieNode *root){
if (this == nullptr)
return false;
for (int i = 0; i < str.length(); i++){
root = root->children[str[i]];
if (root == nullptr)
return false;
}
return root->leaf;
}
TrieNode *buildTrie(){
Utilities ut;
ifstream dictTxt;
dictTxt.open("freq-word.txt");
string line;
while (getline(dictTxt, line)){
string str = ut.rTrim(ut.toUpper(line));
insert(str, root);
}
return root;
}
};