49. Group Anagrams

Medium

1896123FavoriteShare

Given an array of strings, group anagrams together.

Example:


Input:​["eat", "tea", "tan", "ate", "nat", "bat"]​​, Output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ]


class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> result;
if (strs.empty()) { return result; }
unordered_map<string, vector<string>> hashtable;
for (string str : strs) {
string tmp = str;
sort(tmp.begin(), tmp.end());
hashtable[tmp].push_back(str);//插入一个key为tmp,value为增加str的容器
}
for (unordered_map<string, vector<string>>::iterator i = hashtable.begin(); i != hashtable.end(); i++) {
vector<string> sol(i->second.begin(), i->second.end());
result.push_back(sol);
}
return result;
}
};