Group Anagrams
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.
My Code
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
map<vector<int>, vector<string> > m;
map<vector<int>, vector<string> >::iterator it;
for (int i = 0; i < strs.size(); i++)
{
vector<int> cnts(26, 0);
for (int j = 0; j < strs[i].size(); j++)
{
cnts[strs[i][j] - 'a']++;
}
it = m.find(cnts);
if (it != m.end())
it->second.push_back(strs[i]);
else
m.insert(pair<vector<int>, vector<string> >(cnts, vector<string>(strs.begin()+i, strs.begin()+i+1)));
}
vector<vector<string> > groups;
for (it = m.begin(); it != m.end(); it++)
{
sort(it->second.begin(), it->second.end());
groups.push_back(it->second);
}
return groups;
}
};
Runtime: 168 ms