-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem_10.02_groupAnagrams.cc
53 lines (50 loc) · 1.2 KB
/
Problem_10.02_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
#include <algorithm>
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;
class Solution
{
public:
// 排序
vector<vector<string>> groupAnagrams1(vector<string>& strs)
{
unordered_map<string, vector<string>> map;
for (auto& s : strs)
{
string key = s;
std::sort(key.begin(), key.end());
map[key].push_back(s);
}
vector<vector<string>> ans;
for (auto& [key, value] : map)
{
ans.emplace_back(value);
}
return ans;
}
// 计数
vector<vector<string>> groupAnagrams2(vector<string>& strs)
{
// 26 个质数
vector<int> prim = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101};
unordered_map<double, vector<string>> map;
for (auto& s : strs)
{
// 考虑到方法一排序比较耗时,这里借用26个质素任意相乘结果不一,实现 hash 功能
double key = 1.0;
for (char& c : s)
{
key *= (prim[c - 'a']);
}
map[key].push_back(s);
}
vector<vector<string>> ans;
for (auto& [key, value] : map)
{
ans.push_back(value);
}
return ans;
}
};