-
Notifications
You must be signed in to change notification settings - Fork 0
/
trie.cpp
108 lines (97 loc) · 2.23 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
class Node {
public:
Node() { mContent = ' '; mMarker = false; }
~Node() { for(Node* n : mChildren) delete n; }
char content() { return mContent; }
void setContent(char c) { mContent = c; }
bool wordMarker() { return mMarker; }
void setWordMarker() { mMarker = true; }
Node* findChild(char c);
void appendChild(Node* child) { mChildren.push_back(child); }
vector<Node*> children() { return mChildren; }
private:
char mContent;
bool mMarker;
vector<Node*> mChildren;
};
class Trie {
public:
Trie();
~Trie();
void addWord(string s);
bool searchWord(string s);
void deleteWord(string s);
Node* getNodeAt(const string& s);
private:
Node* root;
};
Node* Node::findChild(char c)
{
for (int i = 0; i < mChildren.size(); i++) {
Node* tmp = mChildren.at(i);
if (tmp->content() == c) {
return tmp;
}
}
return NULL;
}
Trie::Trie()
{
root = new Node();
}
Trie::~Trie()
{
// Free memory
delete root;
}
void Trie::addWord(string s)
{
Node* current = root;
if (s.length() == 0) {
current->setWordMarker(); // an empty word
return;
}
for (int i = 0; i < s.length(); i++) {
Node* child = current->findChild(s[i]);
if (child != NULL) {
current = child;
}
else {
Node* tmp = new Node();
tmp->setContent(s[i]);
current->appendChild(tmp);
current = tmp;
}
if (i == s.length() - 1)
current->setWordMarker();
}
}
bool Trie::searchWord(string s)
{
Node* current = root;
while (current != NULL) {
for (int i = 0; i < s.length(); i++) {
Node* tmp = current->findChild(s[i]);
if (tmp == NULL)
return false;
current = tmp;
}
if (current->wordMarker())
return true;
else
return false;
}
return false;
}
Node* Trie::getNodeAt(const string& s) {
Node* current = root;
for (int i = 0; i < s.length(); i++) {
Node* tmp = current->findChild(s[i]);
current = tmp;
}
return current;
}