原题链接:Leecode 49. 字母异位词分组
排序:
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> res;
map<string,vector<string>> m;
int n=strs.size();
for(int i=0;i<n;i++)
{
string s=strs[i];
sort(s.begin(),s.end());
m[s].push_back(strs[i]);
}
for(auto it=m.begin();it!=m.end();it++)
{
res.push_back(it->second);
}
return res;
}
};
计数:
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> res;
map<string,vector<string>> m;
for(auto str: strs)
{
string s=string(26,'0');
for(auto c: str) s[c-'a']++;
m[s].push_back(str);
}
for(auto it=m.begin();it!=m.end();it++)
{
res.push_back(it->second);
}
return res;
}
};