题目:
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:
- For the return value, each inner list's elements must follow the lexicographic order.
- All inputs will be in lower-case.
可以先对字符串进行排序,然后插入到对应的hash表里面,hash表应该是下面的形式:
unordered_map<string, vector<string>> hash;
实现如下:
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> hash;
int i = 0;
for (auto s : strs)
{
sort(s.begin(), s.end());
hash[s].push_back(strs[i++]);
}
vector<vector<string>> res;
for (auto n : hash){
sort(n.second.begin(), n.second.end());
res.push_back(n.second);
}
return res;
}
};