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.
代码:
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> ans;
unordered_map<string, vector<int> > ht;
for(int i = 0; i < strs.size(); i++){
string temp = strs[i];
sort(temp.begin(), temp.end());
ht[temp].push_back(i);
}
for(auto it : ht){
vector<string> temp;
for(int i : it.second)
temp.push_back(strs[i]);
ans.push_back(temp);
}
return ans;
}
};