法一,将字符串排序,放入字典中,将所有的键对应的原字符串列表放入res
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> res;
unordered_map<string,vector<string>> m;//字典:键为排好序的字符串,值为对应该字符串的所有原字符串的列表
for(auto a:strs){
string t=a;//备份,作为键
sort(t.begin(),t.end());//对键字符串排序
m[t].push_back(a);
}
for(auto a:m){
res.bush_back(a.second);
}
return res;
}
};
法二,哈希表排序
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> res;
unordered_map<string, vector<string>> m;
for (string str : strs) {
string t="";
vector<int> hash(26,0);
for(auto c:str) ++hash[c-'a'];
for(auto a:hash) t+=to_string(a);
m[t].push_back(str);
}
for (auto a : m) {
res.push_back(a.second);
}
return res;
}
};