49. Group Anagrams

ss
Feb 9, 2021

--

我一開始還想要全部分開來, 做一個Set但這樣太複雜且太慢了

有個很快的方法, 就是倘若字母集合一樣, 他們排序後一定長的一模一樣

可以利用這點建set

class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> table;
for(int i = 0; i < strs.size();i++){
string t= strs[i];
sort(t.begin(), t.end());
if(table.count(t)){
table[t].push_back(strs[i]);
}else{
table[t] = vector<string>{strs[i]};
}
}
vector<vector<string>> res;
for(auto &i: table){
res.push_back(i.second);
}
return res;
}
};

--

--

ss
ss

No responses yet