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.
class Solution {
public:
/*algorithm
hash strs element to map using lex order string as key
if needs to optimize memory usage, we can store the string index in the table
*/
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>>result;
unordered_map<string,vector<string> >table;
for(int i = 0;i < strs.size();i++){
string key = strs[i];
sort(key.begin(),key.end());
if(table.count(key)){
table[key].push_back(strs[i]);
}else{
vector<string>path(1,strs[i]);
table[key] = path;
}
}
for(auto it = table.begin();it != table.end();it++){
sort((it->second).begin(),(it->second).end());
result.push_back(it->second);
}
return result;
}
};