-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path049.cpp
More file actions
65 lines (57 loc) · 1.46 KB
/
049.cpp
File metadata and controls
65 lines (57 loc) · 1.46 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
#include <iostream>
#include <vector>
#include <map>
using namespace std;
typedef struct cc {
int charcount[26];
bool operator<(const cc& other) const {
for (int i = 0; i < 26; i++) {
if (charcount[i] != other.charcount[i]) {
return charcount[i] < other.charcount[i];
}
}
return false;
}
} cc;
cc statcc(string word) {
cc res;
for (int i = 0; i < 26; i++) {
res.charcount[i] = 0;
}
for (int i = 0; i < word.length(); i++) {
int index = word[i] - 'a';
res.charcount[index] += 1;
}
return res;
}
vector<vector<string> > groupAnagrams(vector<string>& strs) {
map<cc, vector<string> > hash;
vector<vector<string> > res;
for (int i = 0; i < strs.size(); i++) {
string word = strs[i];
cc index = statcc(word);
hash[index].push_back(word);
}
for (auto iter = hash.begin(); iter != hash.end(); iter++) {
res.push_back(iter->second);
}
return res;
}
int main() {
vector<string> strs;
strs.push_back("eat");
strs.push_back("tea");
strs.push_back("tan");
strs.push_back("ate");
strs.push_back("nat");
strs.push_back("bat");
vector<vector<string> > result = groupAnagrams(strs);
for (const auto& group : result) {
cout << "Anagram group: ";
for (const string& word : group) {
cout << word << " ";
}
cout << endl;
}
return 0;
}