-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrie.cpp
executable file
·100 lines (83 loc) · 1.94 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
/*
* File : trie.cpp
* Author : sunowsir
* Mail : [email protected]
* Github : github.com/sunowsir
* Creation : 2021年09月03日 星期五 01时29分44秒
*/
#include <iostream>
#include <vector>
#define BASE 'a'
#define BASE_LEN 26
class Trie {
private:
bool flag;
std::vector<Trie*> next;
public:
Trie();
~Trie();
public:
bool insert(const std::string&);
bool search(const std::string&);
void clear();
};
Trie::Trie() {
this->flag = false;
this->next.reserve(BASE_LEN);
std::vector<Trie*> &n_arr = this->next;
std::vector<Trie*>::iterator i = n_arr.begin();
for (; i != n_arr.end(); i++) {
*i = nullptr;
}
}
Trie::~Trie() {
this->clear();
}
bool Trie::insert(const std::string &ins_str) {
Trie *root = this;
for (int i = 0; i < ins_str.size(); i++) {
Trie* &n_node = root->next[ins_str[i] - BASE];
if (n_node == nullptr)
n_node = new Trie();
root = n_node;
}
root->flag = true;
return true;
}
bool Trie::search(const std::string &srh_str) {
Trie *root = this;
for (int i = 0; i < srh_str.size(); i++) {
Trie* &n_node = root->next[srh_str[i] - BASE];
if (n_node == nullptr)
return false;
root = n_node;
}
return root->flag;
}
void Trie::clear() {
std::vector<Trie*> &n_arr = this->next;
std::vector<Trie*>::iterator i = n_arr.begin();
for(; i != n_arr.end(); i++) {
delete *i;
}
return ;
}
int main() {
Trie *root = new Trie;
char str[100];
int op;
while (scanf("%d%s", &op, str) != EOF) {
switch (op) {
case 1 : {
printf("insert %s to trie\n", str);
root->insert(str);
}break;
case 2 : {
printf("search %s from trie = %d\n", str, root->search(str));
}break;
}
}
root->clear();
delete root;
return 0;
}