-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrieApplication.cpp
More file actions
132 lines (115 loc) · 2.46 KB
/
TrieApplication.cpp
File metadata and controls
132 lines (115 loc) · 2.46 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
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#include "import.h"
using namespace std;
class TrieNode {
public:
char val;
bool isLeaf; // if it is end value of the prefix
int numShared;
vector<TrieNode*> children;
TrieNode() :val(' '), isLeaf(false), numShared(0) {}
TrieNode(char ch) : val(ch), isLeaf(false), numShared(0) {}
TrieNode* subNode(char ch) {
if (!children.empty()) {
for (auto child : children) {
if (child->val == ch)
return child;
}
}
return nullptr;
}
~TrieNode() {
for (auto child : children)
delete child;
}
};
class WordDictionary {
public:
WordDictionary() {
root = new TrieNode();
}
// Inserts a word into the trie.
void addWord(string word) {
//if (searchWord(word)) return;
TrieNode* curr = root;
for (auto ch : word) {
TrieNode* child = curr->subNode(ch);
if (child != nullptr) {
curr = child;
}
else {
TrieNode *newNode = new TrieNode(ch);
curr->children.push_back(newNode);
curr = newNode;
}
++curr->numShared;
}
curr->isLeaf = true;
}
// Returns if the word is in the trie.
bool searchWord(string word) {
TrieNode* curr = root;
for (auto ch : word) {
curr = curr->subNode(ch);
if (curr == nullptr)
return false;
}
return curr->isLeaf == true;
}
bool search(string word) {
return query(word, root);
}
bool query(string word, TrieNode* node) {
if (!node) return false;
TrieNode* curr = node;
int i = 0;
for (auto ch : word) {
i++;
if (ch != '.' && curr) {
curr = curr->subNode(ch);
}
else if (ch == '.' && curr) {
TrieNode* tmp = curr;
if (!tmp->children.empty()) {
for (auto child : tmp->children) {
curr = child;// ->subNode(child->val);
if (query(word.substr(i), child))
return true;
}
}
else {
curr = nullptr;
break;
}
}
else break;
}
return curr && curr->isLeaf == true;
}
bool startsWith(string prefix) {
TrieNode* curr = root;
for (auto ch : prefix) {
curr = curr->subNode(ch);
if (curr == nullptr)
return false;
}
return true;
}
~WordDictionary() {
delete root;
}
private:
TrieNode* root;
};
int main() {
WordDictionary word;
word.addWord("a");
word.addWord("a");
//word.addWord("a");
//word.addWord("a");
//word.search(".");
//word.search("a");
//word.search("aa");
//word.search("a");
//word.search(".a");
cout << word.search("a.");
}