-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathTrie.cpp
More file actions
94 lines (85 loc) · 2.04 KB
/
Trie.cpp
File metadata and controls
94 lines (85 loc) · 2.04 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
const int SZ = 26;
struct Trie {
struct TrieNode {
TrieNode* children[SZ];
int cnt;
TrieNode() {
for(int i = 0; i < SZ; i++)
{
children[i] = nullptr;
}
cnt = 0;
}
};
TrieNode* root = new TrieNode(); // ""
void insert(const string& word)
{
TrieNode* cur = root;
for(int i = 0; i < word.size(); i++)
{
int idx = word[i] - 'a';
cur->cnt++;
if(!cur->children[idx])
{
cur->children[idx] = new TrieNode();
}
cur = cur->children[idx];
}
cur->cnt++;
}
int get_ans(const string& word)
{
TrieNode* cur = root;
for(int i = 0; i < word.size(); i++)
{
int idx = word[i] - 'a';
if(!cur->children[idx]) return 0;
cur = cur->children[idx];
}
return cur->cnt;
}
bool is_empty(TrieNode* cur)
{
if(!cur) return true;
for(int i = 0; i < SZ; i++)
{
if(cur->children[i]) return false;
}
return true;
}
void remove(const string& word)
{
remove(root, word);
}
// void remove(TrieNode* cur, const string& word)
// {
// for(int i = 0; i < word.size(); i++)
// {
// cur->cnt--;
// int idx = word[i] - 'a';
// cur = cur->children[idx];
// }
// cur->cnt--;
// }
TrieNode* remove(TrieNode* cur, const string& word, int idx = 0)
{
cur->cnt--;
if(idx == word.size())
{
if(cur->cnt == 0)
{
delete cur;
cur = nullptr;
}
return cur;
}
int key = word[idx] - 'a';
cur->children[key] = remove(cur->children[key], word, idx+1);
if(is_empty(cur) && cur->cnt == 0)
{
delete cur;
cur = nullptr;
}
return cur;
}
};