-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_0049_groupAnagrams.cc
54 lines (50 loc) · 1022 Bytes
/
Problem_0049_groupAnagrams.cc
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
#include <algorithm>
#include <string>
#include <unordered_map>
#include <vector>
#include "UnitTest.h"
using namespace std;
class Solution
{
public:
vector<vector<string>> groupAnagrams1(vector<string> &strs)
{
unordered_map<string, vector<string>> map;
for (auto &s : strs)
{
string cur;
int cnt[256] = {0};
for (char &c : s)
{
cnt[c - 'a']++;
}
for (int i = 0; i < 256; i++)
{
cur += std::to_string(cnt[i]) + "_";
}
map[cur].push_back(s);
}
vector<vector<string>> ans;
for (auto &e : map)
{
ans.push_back(e.second);
}
return ans;
}
vector<vector<string>> groupAnagrams2(vector<string> &strs)
{
unordered_map<string, vector<string>> map;
for (auto &s : strs)
{
string cur = s;
std::sort(cur.begin(), cur.end());
map[cur].push_back(s);
}
vector<vector<string>> ans;
for (auto &e : map)
{
ans.push_back(e.second);
}
return ans;
}
};