-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
57 lines (48 loc) · 1.4 KB
/
main.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> mp;
for (const string& s : strs) {
array<int, 26> cnt;
cnt.fill(0);
for (char c : s) ++cnt[c - 'a'];
string k;
for (int v : cnt) k += to_string(v) + ':';
mp[k].push_back(s);
}
vector<vector<string>> result;
for (auto [k, v] : mp) result.push_back(v);
return result;
}
};
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> mp;
for (const string& s : strs) {
string k = s;
sort(k.begin(), k.end());
mp[k].push_back(s);
}
vector<vector<string>> result;
for (auto [_, v] : mp) result.push_back(v);
return result;
}
};
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> result;
unordered_map<string, int> group;
for (string& v : strs) {
string k = v;
sort(k.begin(), k.end());
if (group.count(k) == 0) {
group[k] = group.size();
result.push_back({});
}
result[group[k]].push_back(v);
}
return result;
}
};