-
Notifications
You must be signed in to change notification settings - Fork 1
/
solution.cpp
executable file
·72 lines (54 loc) · 1.33 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
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;
class TrieNode {
public:
vector<TrieNode*> children;
TrieNode() {
children.resize(26);
}
};
void insert(TrieNode* root, string key) {
TrieNode* traverse = root;
// add the key reversly
for (int i = key.size() - 1; i >= 0; i--) {
if (traverse->children[key[i] - 'a'] == NULL)
traverse->children[key[i] - 'a'] = new TrieNode();
traverse = traverse->children[key[i] - 'a'];
}
}
bool search(TrieNode* root, string key) {
TrieNode* traverse = root;
// search the key until its middle
for (int i = 0; i < (key.size() + 1) / 2; i++) {
if (traverse->children[key[i] - 'a'] == NULL)
return false;
traverse = traverse->children[key[i] - 'a'];
}
return true;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
TrieNode* root = new TrieNode();
int n;
cin >> n;
vector<string> strList;
while (n--) {
string s;
cin >> s;
strList.push_back(s);
insert(root, s);
}
int result = 0;
for (string& str : strList) {
if (search(root, str))
result++;
}
cout << result << endl;
return 0;
}