-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathGroup Anagrams
More file actions
44 lines (36 loc) · 1.21 KB
/
Group Anagrams
File metadata and controls
44 lines (36 loc) · 1.21 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
/****************************************************************************************
Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
Note:
For the return value, each inner list's elements must follow the lexicographic order.
All inputs will be in lower-case.
****************************************************************************************/
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
int m = strs.size();
vector<vector<string>> result;
unordered_map<string,vector<int>> table(m);
vector<string> str(strs); //copy the data.
for(int i = 0;i<m;i++)
{
sort(str[i].begin(),str[i].end());
table[str[i]].push_back(i);
}
for(auto it = table.begin();it!=table.end();it++)
{
vector<string> tmp;
for(int i = 0;i<it->second.size();i++)
tmp.push_back(strs[it->second[i]]);
sort(tmp.begin(),tmp.end());
result.push_back(tmp);
}
return result;
}
};