-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgroup_anagrams.cpp
More file actions
78 lines (71 loc) · 1.98 KB
/
group_anagrams.cpp
File metadata and controls
78 lines (71 loc) · 1.98 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*
* =====================================================================================
*
* Filename: group_anagrams.cpp
*
* Description: 49. Group Anagrams.
* Given an array of strings, group anagrams together.
*
* Version: 1.0
* Created: 05/09/2019 12:59:34 PM
* Revision: none
* Compiler: gcc
*
* Author: YOUR NAME (),
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <unordered_map>
class Solution
{
public:
std::vector<std::vector<std::string>> groupAnagrams(std::vector<std::string>& strs)
{
std::unordered_map<std::string, std::vector<std::string>> anagram_map;
for (auto& s: strs)
{
auto key = getAnagramKey(s);
auto ret_pair = anagram_map.insert(std::make_pair(key, std::vector<std::string>({s})));
if (!ret_pair.second)
{
ret_pair.first->second.push_back(s);
}
}
std::vector<std::vector<std::string>> anagram_vect;
for (auto& item: anagram_map)
{
anagram_vect.push_back(item.second);
}
return anagram_vect;
}
private:
std::string getAnagramKey(const std::string& str)
{
const int letter_size = 26;
int counts[letter_size] = {0};
for (char chr: str)
{
counts[chr - 'a'] += 1;
}
std::string key;
for (int i = 0; i < letter_size; i++)
{
if (counts[i] > 0)
{
key.append(counts[i], (char)(i + 'a'));
}
}
return key;
}
};
int main(int argc, char* argv[])
{
std::vector<std::string> strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
auto anagrams = Solution().groupAnagrams(strs);
printf("Group size of anagrams: %zd\n", anagrams.size());
return 0;
}