-
Notifications
You must be signed in to change notification settings - Fork 0
/
049. Group Anagrams.cpp
40 lines (38 loc) · 1.04 KB
/
049. Group Anagrams.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
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>>res;
unordered_map<string, vector<string>>m;
for(auto s: strs){
string tmp = s;
sort(tmp.begin(), tmp.end());
m[tmp].push_back(s);
}
for(auto x: m) res.push_back(x.second);
return res;
}
};
// Implement an O(n) sort() function myself.
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>>res;
unordered_map<string, vector<string>>m;
for(auto s: strs){
string tmp = s;
sortStr(tmp);
m[tmp].push_back(s);
}
for(auto x: m) res.push_back(x.second);
return res;
}
void sortStr(string& s){
unordered_map<char, int>m;
for(auto c: s) m[c]++;
string res = "";
for(int i = 0; i < 26; i++){
while(m['a' + i]-- > 0) res.push_back('a' + i);
}
s = res;
}
};