-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGroupAnagrams.cpp
More file actions
55 lines (48 loc) · 1.24 KB
/
GroupAnagrams.cpp
File metadata and controls
55 lines (48 loc) · 1.24 KB
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
// solution 1
class Solution1 {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
map<map<char, int>, vector<string>> word_map;
vector<vector<string>> result;
for (auto s : strs)
{
map<char, int> cur;
for (auto c : s)
{
cur[c] += 1;
}
if (word_map.find(cur) != word_map.end())
{
word_map[cur].push_back(s);
}
else
{
word_map[cur] = {s};
}
}
for (auto iter = word_map.begin(); iter != word_map.end(); iter++)
{
result.push_back(iter->second);
}
return result;
}
};
// solution 2
class Solution2 {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> word_map;
vector<vector<string>> result;
for (auto s : strs)
{
auto t = s;
sort(s.begin(), s.end());
word_map[s].push_back(t);
}
for (auto iter = word_map.begin(); iter != word_map.end(); iter++)
{
result.push_back(iter->second);
}
return result;
}
};