Skip to content

Instantly share code, notes, and snippets.

@safeng
Created January 24, 2014 04:07
Show Gist options
  • Save safeng/8591941 to your computer and use it in GitHub Desktop.
Save safeng/8591941 to your computer and use it in GitHub Desktop.
Given an array of strings, return all groups of strings that are anagrams. Note: All inputs will be in lower-case.
class Solution {
public:
vector<string> anagrams(vector<string> &strs) {
// find distribution or sort
vector<string> res;
int n = strs.size();
// sort each string in string array
// use hash to find equal elements of two arrays or duplicate elements in one array
unordered_map<string, int> dict;
for(int i = 0; i<n; ++i)
{
string s = strs[i];
sort(s.begin(), s.end());
if(dict.find(s) == dict.end()) // new
{
dict.insert(make_pair(s, i));
}else
{
if(dict[s]>=0)
{
res.push_back(strs[dict[s]]);
dict[s] = -1;
}
res.push_back(strs[i]);
}
}
return res;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment