Problem Statement could be found @https://leetcode.com/problems/anagrams/
Approach -
1. To put all anagrams of a string together we need some way to bucket, so that all anagrams land up in same bucket
2. To get to bucket we can use integer hashing but problem there would be collision.
3. To avoid collision we are using a string key (acting as a hash). For each string we take the smallest string lexicographic-ally which can be created from it as the hash key and store the all strings which have occurred so far.
Following is the code snippet
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
map<string, vector<string>> m;
for (int i=0; i<strs.size();i++){
string s = strs[i];
sort(s.begin(), s.end());
vector<string> v;
if(m.count(s) >0){
v = m[s];
}
v.push_back(strs[i]);
m[s]=v;
}
vector<vector<string>> retvec;
for(auto a=m.begin(); a!= m.end(); a++){
retvec.push_back(a->second);
}
return retvec;
}
};
Approach -
1. To put all anagrams of a string together we need some way to bucket, so that all anagrams land up in same bucket
2. To get to bucket we can use integer hashing but problem there would be collision.
3. To avoid collision we are using a string key (acting as a hash). For each string we take the smallest string lexicographic-ally which can be created from it as the hash key and store the all strings which have occurred so far.
Following is the code snippet
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
map<string, vector<string>> m;
for (int i=0; i<strs.size();i++){
string s = strs[i];
sort(s.begin(), s.end());
vector<string> v;
if(m.count(s) >0){
v = m[s];
}
v.push_back(strs[i]);
m[s]=v;
}
vector<vector<string>> retvec;
for(auto a=m.begin(); a!= m.end(); a++){
retvec.push_back(a->second);
}
return retvec;
}
};