-
Notifications
You must be signed in to change notification settings - Fork 138
/
Solution.cpp
108 lines (88 loc) · 2.35 KB
/
Solution.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
100
101
102
103
104
105
106
107
108
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;
struct TrieNode {
string value;
unordered_map<char, TrieNode *> children = {};
int size = 0;
};
class Trie {
public:
TrieNode *root = new TrieNode;
TrieNode *find(string query);
int countPartialFind(string query);
void add(string value);
private:
void add(string value, TrieNode *node);
TrieNode *createNewNode(string &value, int counter, unordered_map<char, TrieNode *> &children);
void add(string value, int counter, TrieNode *node);
TrieNode *findNode(char query, unordered_map<char, TrieNode *> &children);
};
TrieNode *Trie::find(string value) {
TrieNode *tmpNode = root;
for (int counter = 0; counter < value.length(); counter++) {
tmpNode = findNode(value[counter], tmpNode->children);
if (tmpNode == NULL) {
return NULL;
}
}
return tmpNode;
}
int Trie::countPartialFind(string query) {
TrieNode *matchNode = find(query);
if (matchNode == NULL) {
return 0;
}
return matchNode->size;
}
void Trie::add(string value, int counter, TrieNode *node) {
for (; counter < value.length(); counter++) {
node->size++;
TrieNode *tmpNode = findNode(value[counter], node->children);
if (tmpNode == NULL) {
node = createNewNode(value, counter, node->children);
} else {
node = tmpNode;
}
}
node->size++;
}
TrieNode *Trie::findNode(char query, unordered_map<char, TrieNode *> &children) {
unordered_map<char, TrieNode *>::const_iterator search = children.find(query);
if (search == children.end()) {
return NULL;
}
return search->second;
}
TrieNode *Trie::createNewNode(string &value, int counter, unordered_map<char, TrieNode *> &children) {
TrieNode *newNode = new TrieNode;
newNode->value = value.substr(0, counter + 1);
char tmp = value[counter];
children[tmp] = newNode;
return newNode;
}
void Trie::add(string value) {
if (value.length() == 0) { return; }
add(value, 0, root);
}
int main() {
Trie *t = new Trie;
int nr;
cin >> nr;
while (nr > 0) {
string query, value;
cin >> query >> value;
if (query == "add") {
t->add(value);
}
if(query == "find") {
cout << t->countPartialFind(value) << "\n";
}
nr--;
}
return 0;
}