Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
Return:
[ ["ate", "eat","tea"], ["nat","tan"], ["bat"] ]
Note: All inputs will be in lower-case.
解法一:
首先把有序的string排序,作为hash table的key,然后把anagrams在结果中的存储index作为每一个bucket的key。
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> res;
unordered_map<string, int> m;
int idx = 0;
for(int i=0; i<strs.size(); i++){
string s = strs[i];
sort(s.begin(),s.end());
if(m.find(s)==m.end()){
vector<string> tmp(1,strs[i]);
res.push_back(tmp);
m[s] = idx;
idx++;
}else{
res[m[s]].push_back(strs[i]);
}
}
return res;
}
};