-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest3.cpp
More file actions
60 lines (56 loc) · 1.17 KB
/
test3.cpp
File metadata and controls
60 lines (56 loc) · 1.17 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
#include <iostream>
#include <string>
#include <deque>
using string = std::string;
class Trie {
private:
constexpr static int CHAR_NUM = 26;
Trie* links[CHAR_NUM];
bool isEnd;
Trie* searchPrefix(string word) {
Trie* node = this;
for (char ch: word) {
if (node.containsKey(ch)) {
node = node.get(ch);
} else {
return nullptr;
}
}
return node;
}
public:
bool containsKey(char ch) {
return links[ch - 'a'] != nullptr;
}
void put(char ch, Trie* node) {
links[ch - 'a'] = node;
}
void setEnd() {
isEnd = true;
}
void insert(string word) {
Trie* node = this;
for (char ch: word) {
if (!node.containsKey(ch)) {
node.put(ch, new Trie());
}
node = node.get(ch);
}
node.setEnd();
}
bool search(string word) {
Trie* node = searchPrefix(word);
return node != nullptr && node.isEnd();
}
bool startsWith(string word) {
Trie* node = searchPrefix(word);
return node != nullptr;
}
~Trie() {
std::deque<Trie*> stack;
}
};
int main() {
Trie t;
return 0;
}