给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
字母异位词 是由重新排列源单词的所有字母得到的一个新单词。
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
//用hash存储异位词,key为排序后的字符,value为异位词
unordered_map<string,vector<string>>mp;
//遍历字符串数组
for(auto &str:strs){
//以当前字符串为key
string key=str;
//对key排序
sort(key.begin(),key.end());
//在hash表中以排序后的字符串为key插入str
mp[key].push_back(str);
}
//输出
vector<vector<string>>ans;
//遍历哈希表
for(auto &pair:mp){
//将hash表的value插入ans
ans.push_back(pair.second);
}
//返回ans
return ans;
}
};

被折叠的 条评论
为什么被折叠?



