forked from codereport/HackerRank
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHourRank_30_P1.cpp
More file actions
63 lines (57 loc) · 1.46 KB
/
Copy pathHourRank_30_P1.cpp
File metadata and controls
63 lines (57 loc) · 1.46 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
// code_report Solution
// Solution 1:
// https://youtu.be/uOG3QyxIjso
vector<string> solve (vector<string> names) {
unordered_set<string> s;
unordered_map<string, int> m;
vector<string> ans;
for (const auto& name : names) {
auto it = m.find (name);
if (it != m.end ()) {
it->second++;
ans.push_back (name + ' ' + to_string (it->second));
}
else {
m[name] = 1;
string t;
bool inserted = false;
for (auto c : name) {
t += c;
auto p = s.insert (t);
if (!inserted && p.second) {
inserted = true;
ans.push_back (t);
}
}
if (!inserted) ans.push_back (t); // very tricky case
}
}
return ans;
}
// Solution 2 (Trie):
// https://youtu.be/VsiP-dTWyG4?t=249
struct trie {
unordered_map<char, trie*> m;
int count = 0;
};
vector<string> solve(vector<string> names) {
auto* t = new trie();
vector<string> res;
for (const auto& name : names) {
auto* node = t;
auto added = false;
auto p = ""s;
for (auto c : name) {
p += c; // prefix
if (!node->m.count(c)) {
if (!added) res.push_back(p), added = true;
node->m[c] = new trie();
}
node = node->m[c];
}
node->count++;
if (!added)
res.push_back(p + (node->count != 1 ? " " + to_string(node->count) : ""));
}
return res;
}