题目
算法
http://blog.csdn.net/guang09080908/article/details/47976481
- 先对字符排序,然后存储到hashmap,然后跟剩余的字符(先排序)对比,相等的存入到map中
o(n)
代码
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> hashMap;
for(auto &v : strs) {
string tmp(v);
sort(tmp.begin(), tmp.end());
hashMap[tmp].push_back(v);
}
vector<vector<string>> result(hashMap.size());
int k = 0;
for(auto it = hashMap.begin(); it != hashMap.end(); ++it, ++k) {
result[k].swap(it->second);
sort(result[k].begin(), result[k].end());
}
return result;
}
};