forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathgroup-anagrams.cpp
More file actions
26 lines (23 loc) · 736 Bytes
/
group-anagrams.cpp
File metadata and controls
26 lines (23 loc) · 736 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
// Time: O(n * glogg), g is the max size of groups.
// Space: O(n)
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> groups;
for (const auto& str : strs) {
string tmp{str};
sort(tmp.begin(), tmp.end());
groups[tmp].emplace_back(str);
}
vector<vector<string>> anagrams;
for (const auto& kvp : groups) {
vector<string> group;
for (const auto& str : kvp.second) {
group.emplace_back(str);
}
sort(group.begin(), group.end());
anagrams.emplace_back(move(group));
}
return anagrams;
}
};