-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path49.cpp
43 lines (42 loc) · 1.1 KB
/
49.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
// sort_hash.cpp
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, int> map;
vector<vector<string>> res;
for (int i = 0, count = 0; i < strs.size(); ++i) {
string newstr = strs[i];
ranges::sort(newstr);
auto it = map.find(newstr);
if (it == map.end()) {
map[newstr] = count++;
res.push_back({strs[i]});
} else {
res[it->second].push_back(strs[i]);
}
}
return res;
}
};
// encode
class Solution2 {
string encode(const string& s) {
string res(26, 0);
for (char c : s) {
++res[c - 'a'];
}
return res;
}
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> mp;
for (auto& s : strs) {
mp[encode(s)].push_back(s);
}
vector<vector<string>> res;
for (auto& [k, v] : mp) {
res.push_back(move(v));
}
return res;
}
};