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.
// Usage of HashMap.
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_map>
using namespace std;
vector< vector<string> > groupAnagrams(vector<string>& strs) {
if(strs.size() == 0) return {{}};
vector< vector<string> > res;
unordered_map<string, vector<string> > map;
for(int i = 0; i < strs.size(); ++i) {
string tmp = strs[i];
sort(tmp.begin(), tmp.end()); // this is the key point.
auto iter = map.find(tmp);
if(iter == map.end()) {
map.insert({tmp, {strs[i]}}); // make_pair {}
} else {
(iter->second).push_back(strs[i]);
}
}
auto it = map.begin();
while(it != map.end()) {
sort(it->second.begin(), it->second.end()); // sort them in lexicographic order.
res.push_back(it->second);
it++;
}
return res;
}
int main(void) {
vector<string> inputs{"eat", "tea", "tan", "ate", "nat", "bat"};
vector< vector<string> > res = groupAnagrams(inputs);
for(int i = 0; i < res.size(); ++i) {
for(int j = 0; j < res[i].size(); ++j) {
cout << res[i][j] << endl;
}
cout << endl;
}
cout << endl;
}