Given an array of strings, group anagrams together.
Input: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],
Output:
[
[“ate”,“eat”,“tea”],
[“nat”,“tan”],
[“bat”]
]
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> mmap;
for(int i =0; i < strs.size(); i++){
string str = strs[i];
sort(str.begin(), str.end());
if(mmap.find(str) != mmap.end()){
mmap[str].push_back(strs[i]);
} else{
vector<string> temp = {strs[i]};
mmap[str] = temp;
}
}
// iter the all keys
vector<vector<string>> res;
for(unordered_map<string, vector<string>>::iterator iter = mmap.begin(); iter != mmap.end(); iter++){
res.push_back(iter -> second);
}
return res;
}
};