Sort each string as the key to the map.
Bucket sort:
class Solution {
public:
vector<string> anagrams(vector<string> &strs) {
map<string, vector<string> > dict;
vector<string> result;
for(int i=0;i<strs.size();i++) {
string key = sortChars(strs[i]);
dict[key].push_back(strs[i]);
}
for(map<string,vector<string> >::iterator it = dict.begin(); it!=dict.end();it++) {
if((it->second).size()>1) {
for(int j=0;j<(it->second).size();j++)
result.push_back((it->second)[j]);
}
}
return result;
}
string sortChars(string str) {
int char_set[26]={0};
for(int i=0;i<str.length();i++) {
char_set[str[i]-'a']++;
}
string res="";
for(int i=0;i<26;i++) {
char c = 'a' + i;
for(int j=0;j<char_set[i];j++)
res = res + c;
}
return res;
}
};
Or we can use the built-in quick sort
class Solution {
public:
vector<string> anagrams(vector<string> &strs) {
map<string, vector<int>> group;
map<string, vector<int>>:: iterator git;
vector<string> tmp(strs);
vector<string>::iterator itr;
for(itr=tmp.begin();itr!=tmp.end();itr++) {
sort((*itr).begin(),(*itr).end());
}
int index=0;
for(itr=tmp.begin();itr!=tmp.end();itr++,index++) {
group[*itr].push_back(index);
}
vector<string> result;
for(git=group.begin();git!=group.end();git++) {
int cnt=(git->second).size();
if(cnt>1) {
for(int i=0;i<cnt;i++)
result.push_back(strs[git->second[i]]);
}
}
return result;
}
};