题目: 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:
1.For the return value,each inner list’s elements must follow the lexicographic order.
2.All inputs will be in lower-case.
思路: 哈希表实现
class Solution {
public:
@H_404_27@vector<@H_404_27@vector<@H_404_27@string>> groupAnagrams(@H_404_27@vector<@H_404_27@string>& strs) {
@H_404_27@vector<@H_404_27@vector<@H_404_27@string>> result;
@H_404_27@unordered_map<@H_404_27@string,int> hashmap;
@H_404_27@string temp;
int pos=0;
for(int i=0;i<strs.size();++i)
{
temp=strs[i];
sort(temp.begin(),temp.end());
if(hashmap.find(temp)==hashmap.end())
{
hashmap[temp]=pos++;
result.push_back(@H_404_27@vector<@H_404_27@string>(1,strs[i]));
}
else
{
result[hashmap[temp]].push_back(strs[i]);
}
}
for(int i=0;i<result.size();++i)
sort(result[i].begin(),result[i].end());
return result;
}
};