[Problem]
[Solution]
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
[Solution]
class Solution {说明:版权所有,转载请注明出处。 Coder007的博客
public:
// get hash value of a string
int hashValue(string &str){
// prime numbers
int prime[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101};
int value = 1;
// calculate
for(int i = 0; i < str.size(); ++i){
value *= prime[str[i] - 'a'];
}
return value;
}
// anagrams
vector<string> anagrams(vector<string> &strs) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
// variables definition
vector<string> res;
map<int, vector<string> > strMap;
map<int, vector<string> >::iterator it;
// calculate hash value of each string
for(int i = 0; i < strs.size(); ++i){
int key = hashValue(strs[i]);
it = strMap.find(key);
if(it == strMap.end()){
vector<string> tmp;
tmp.push_back(strs[i]);
strMap.insert(make_pair(key, tmp));
}
else{
it->second.push_back(strs[i]);
}
}
// add result
for(it = strMap.begin(); it != strMap.end(); ++it){
if(it->second.size() > 1){
for(int i = 0; i < it->second.size(); ++i){
res.push_back((it->second)[i]);
}
}
}
return res;
}
};