forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgroup-shifted-strings.cpp
More file actions
31 lines (27 loc) · 848 Bytes
/
group-shifted-strings.cpp
File metadata and controls
31 lines (27 loc) · 848 Bytes
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
// Time: O(nlogn)
// Space: O(n)
class Solution {
public:
vector<vector<string>> groupStrings(vector<string>& strings) {
unordered_map<string, multiset<string>> groups;
for (const auto& str : strings) { // Grouping.
groups[hashStr(str)].insert(str);
}
vector<vector<string>> result;
for (const auto& kvp : groups) {
vector<string> group;
for (auto& str : kvp.second) { // Sorted in a group.
group.emplace_back(move(str));
}
result.emplace_back(move(group));
}
return result;
}
string hashStr(string str) {
const char base = str[0];
for (auto& c : str) {
c = 'a' + ((c - base) >= 0 ? c - base : c - base + 26);
}
return str;
}
};