-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontacts.cpp
More file actions
58 lines (52 loc) · 1.21 KB
/
contacts.cpp
File metadata and controls
58 lines (52 loc) · 1.21 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
// Author: btjanaka (Bryon Tjanaka)
// Problem: (HackerRank) contacts
// Title: Contacts
// Link: https://www.hackerrank.com/challenges/contacts/problem
// Idea: Construct a trie and use that to perform all operations.
// Difficulty: medium
// Tags: trie, string
#include <bits/stdc++.h>
using namespace std;
struct Node {
int count;
vector<Node*> children;
Node() : count(0), children(26, nullptr) {}
};
struct Trie {
Trie() : root(new Node()) {}
Node* root;
void add(const string& name) {
++(root->count);
Node* cur = root;
for (int i = 0; i < name.size(); ++i) {
int idx = name[i] - 'a';
if (cur->children[idx] == nullptr) cur->children[idx] = new Node();
cur = cur->children[idx];
++(cur->count);
}
}
int find(const string& name) {
Node* cur = root;
for (int i = 0; i < name.size(); ++i) {
int idx = name[i] - 'a';
if (cur->children[idx] == nullptr) return 0;
cur = cur->children[idx];
}
return cur->count;
}
};
int main() {
int n;
cin >> n;
Trie trie;
while (n--) {
string cmd, name;
cin >> cmd >> name;
if (cmd == "add")
trie.add(name);
else {
cout << trie.find(name) << "\n";
}
}
return 0;
}