Skip to content

Instantly share code, notes, and snippets.

@pdu
Created December 29, 2012 04:14
Show Gist options
  • Select an option

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

Select an option

Save pdu/4404519 to your computer and use it in GitHub Desktop.
Given an array of strings, return all groups of strings that are anagrams. http://www.leetcode.com/onlinejudge
#include <algorithm>
#include <vector>
#include <string>
#include <tr1/unordered_map>
using namespace std;
class Solution {
public:
vector<string> anagrams(vector<string> &strs) {
vector<string> ret;
tr1::unordered_map<string, int> flag;
tr1::unordered_map<string, int>::iterator it;
for (int i = 0; i < strs.size(); ++i) {
string tmp = strs[i];
sort(tmp.begin(), tmp.end());
it = flag.find(tmp);
if (it == flag.end()) {
flag[tmp] = i;
}
else {
if (it->second != -1) {
ret.push_back(strs[it->second]);
}
ret.push_back(strs[i]);
it->second = -1;
}
}
return ret;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment