Created
January 24, 2014 04:07
-
-
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.
This file contains 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
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