版权声明:by ruohua3kou https://blog.csdn.net/ruohua3kou/article/details/88963878
对每一个字符串的排序作为哈希表的索引,将字符相同的存到哈希表中对应索引的值中
在discuss中看到一个排序string的函数(限于字符全为小写),加了进来以减少时间复杂度
class Solution
{
public:
vector<vector<string>> groupAnagrams(vector<string> &strs)
{
unordered_map<string, vector<string>> mapping;
for (string str : strs)
{
mapping[sortstr(str)].push_back(str);
}
vector<vector<string>> res;
for (auto m : mapping)
{
res.push_back(m.second);
}
return res;
}
string sortstr(string str)
{
char counter[26] = {0};
for (char c : str)
{
counter[c - 'a']++;
}
string res;
for (int i = 0; i < 26; i++)
{
res += string(counter[i], i + 'a');
}
return res;
}
};