Given an arrayof 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:
string helpSort(string str){
vector<int> countv(26, 0);
for(int i = 0; i < str.size(); ++i){
++countv[str[i]-'a'];
}
string res = "";
for(int i = 0; i < 26; ++i){
while(countv[i]--)
res += 'a'+i;
}
return res;
}
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> res;
if(strs.size() < 1)
return res;
unordered_map<string, vector<string>> mm;
for(string str : strs){
string tmp = str;
tmp = helpSort(tmp);
mm[tmp].push_back(str);
}
for(auto m : mm){
res.push_back(m.second);
}
return res;
}
};