-
Notifications
You must be signed in to change notification settings - Fork 0
/
group_anagrams.cpp
45 lines (37 loc) · 924 Bytes
/
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
/*
49. Group Anagrams
Medium
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:
All inputs will be in lowercase.
The order of your output does not matter.
*/
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& str) {
vector<vector<string>> result;
if(str.size()==0)
return result;
map<string, vector<string>> m;
for(int i=0;i<str.size();i++){
string sorted = str[i];
sort(sorted.begin(),sorted.end());
if(m.find(sorted)!=m.end()){
m.insert({sorted,vector<string> ()});
}
m[sorted].push_back(str[i]);
}
for(auto &val : m){
result.push_back(val.second);
}
return result;
}
};