-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path00049-group_anagrams.cpp
51 lines (40 loc) · 1.06 KB
/
00049-group_anagrams.cpp
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
// 49: Group Anagrams
// https://leetcode.com/problems/group-anagrams/
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
class Solution {
public:
// SOLUTION
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> result;
unordered_map<string, vector<string>> tmap;
for(int i=0; i<strs.size(); i++) {
string str = strs[i];
sort(strs[i].begin(), strs[i].end());
tmap[strs[i]].push_back(str);
}
for(auto i=tmap.begin(); i!=tmap.end(); i++)
result.push_back(i->second);
return result;
}
};
int main() {
Solution o;
// INPUT
vector<string> strs = {"eat","tea","tan","ate","nat","bat"};
// OUTPUT
auto result = o.groupAnagrams(strs);
cout<<"[";
for (auto g : result) {
cout<< "[";
for (auto s : g) {
cout << "\"" << s << "\",";
}
cout << "\b],";
}
cout << "\b]" << endl;
return 0;
}