Skip to content

Instantly share code, notes, and snippets.

@pdu
Created February 17, 2013 13:41
Show Gist options
  • Select an option

  • Save pdu/4971536 to your computer and use it in GitHub Desktop.

Select an option

Save pdu/4971536 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. http://leetcode.com/onlinejudge#question_49
class Solution {
public:
vector<string> anagrams(vector<string> &strs) {
vector<string> ans;
map<string, int> M;
for (int i = 0; i < strs.size(); ++i) {
string tmp = strs[i];
sort(tmp.begin(), tmp.end());
try {
M[tmp]++;
}
catch (exception& e) {
M[tmp] = 1;
}
}
for (int i = 0; i < strs.size(); ++i) {
string tmp = strs[i];
sort(tmp.begin(), tmp.end());
if (M[tmp] >= 2)
ans.push_back(strs[i]);
}
return ans;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment