Created
December 29, 2012 04:14
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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