LeetCode 49. Group Anagrams

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> m;
for (string &s : strs) {
string key = s;
sort(key.begin(), key.end());
m[key].emplace_back(s);
}
vector<vector<string>> ans(m.size());
int i = 0;
for (auto [_, s] : m)
ans[i++] = move(s);
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> m;
for (string &s : strs) {
m[strSort(s)].emplace_back(s);
}
vector<vector<string>> ans(m.size());
int i = 0;
for (auto [_, s] : m)
ans[i++] = move(s);
return ans;
}
string strSort(string &s) {
int cnt[26] = {0};
for (auto &c : s)
++cnt[c - 'a'];
string ans;
for (int i = 0; i < 26; i++)
ans += string(cnt[i], i + 'a');
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> m;
for (string &s : strs) {
m[strCnt(s)].emplace_back(s);
}
vector<vector<string>> ans(m.size());
int i = 0;
for (auto [_, s] : m)
ans[i++] = move(s);
return ans;
}
string strCnt(string &s) {
int cnt[26] = {0};
for (auto &c : s)
++cnt[c - 'a'];
string ans;
for (int i = 0; i < 26; i++)
ans += (i + 'a') + cnt[i];
return ans;
}
};