-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrie.cpp
More file actions
90 lines (90 loc) · 1.41 KB
/
Trie.cpp
File metadata and controls
90 lines (90 loc) · 1.41 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
class Trie //https ://github.com/seo-bo/Algorithm_templates/blob/main/Trie.cpp
{
private:
struct Node
{
bool fin;
map<char, Node*>child;
Node() { fin = false; }
};
Node* root;
void destroy(Node* node)
{
if (node)
{
for (auto& [_, a] : node->child)
{
destroy(a);
}
delete node;
}
}
bool del(Node* node, const string& word, int depth)
{
if (!node)
{
return false;
}
if (depth == word.size())
{
if (node->fin)
{
node->fin = false;
return node->child.empty();
}
return false;
}
char pivot = word[depth];
if (del(node->child[pivot], word, depth + 1))
{
delete node->child[pivot];
node->child.erase(pivot);
return (!node->fin && node->child.empty());
}
return false;
}
void add(const string& word)
{
Node* cur = root;
for (auto& i : word)
{
if (cur->child.find(i) == cur->child.end())
{
cur->child[i] = new Node();
}
cur = cur->child[i];
}
cur->fin = true;
}
bool search(const string& word)
{
Node* cur = root;
for (auto& i : word)
{
if (cur->child.find(i) == cur->child.end())
{
return false;
}
cur = cur->child[i];
}
return (cur && cur->fin);
}
public:
Trie() { root = new Node(); }
void finish()
{
destroy(root);
}
void insert(const string& word)
{
add(word);
}
bool pop(const string& word)
{
return del(root, word, 0);
}
bool find(const string& word)
{
return search(word);
}
};