-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path49.group-anagrams.cpp
More file actions
62 lines (48 loc) · 1.25 KB
/
49.group-anagrams.cpp
File metadata and controls
62 lines (48 loc) · 1.25 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
56
57
58
59
60
61
/*
* @lc app=leetcode id=49 lang=cpp
*
* [49] Group Anagrams
*/
// @lc code=start
#include <algorithm>
#include <iostream>
#include <memory.h>
#include <stack>
#include <unordered_map>
#include <utility>
#include <vector>
#include <array>
using namespace std;
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> result;
array<int, 26> cnts;
unordered_map<string, vector<string>> map;
for (int i = 0; i < strs.size(); i++) {
fill(cnts.begin(), cnts.end(), 0);
const string str = strs[i];
for (int j = 0; j < str.size(); j++) {
cnts[str.at(j) - 'a']++;
}
string hashKey = "";
for (int i = 0; i < cnts.size(); i++) {
hashKey += "#" + to_string(cnts[i]);
}
if(map.find(hashKey) != map.end()) {
map.at(hashKey).push_back(str);
}
else {
map.insert({hashKey, vector {str}});
}
}
auto it = map.begin();
while(it != map.end())
{
result.push_back(it->second);
it++;
}
return result;
}
};
// @lc code=end