-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path49.cpp
More file actions
53 lines (47 loc) · 1.07 KB
/
49.cpp
File metadata and controls
53 lines (47 loc) · 1.07 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
/*
49. Group Anagrams
Given an array of strings strs, group the
anagrams together. You can return the answer in any order.
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_map>
using namespace std;
/*
time: O(nklogk), k is the length of the word.
space: O(n*k)
*/
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> dic;
for (string str : strs) {
string tmp = str;
sort(str.begin(), str.end());
dic[str].push_back(tmp);
}
vector<vector<string>> ret;
for (auto elem : dic) {
ret.push_back(elem.second);
}
return ret;
}
template <typename T>
void printVecVec(const vector<vector<T>>& vec) {
for (const auto& v : vec) {
for (const auto& elem : v) {
cout << elem << " ";
}
cout << endl;
}
}
void test() {
vector<string> strs;
strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
vector<vector<string>> ret = groupAnagrams(strs);
printVecVec(ret);
}
int main()
{
test();
return 0;
}