题目描述:
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
思路:
题目的意思呢,就是寻找一组字符串中,字符串使用相同数量的相同字符的两个字符串互为anagrams,把这样的字符串输出。
明白了题目的意思,我们可以对每个字符串进行排序,然后将排序后的字符串作为该字符串的哈希值,保存每个哈希值的所有字符串。如果该哈希值的字符串的个数大于1,也就是说存在anagrams
代码:
class Solution {
public:
vector<string> anagrams(vector<string> &strs) {
map<string,vector<string> > map_str;
vector<string> vec_str;
for(int i =0;i<strs.size();i++){
string temp= strs[i];
sort(temp.begin(),temp.end());
map_str[temp].push_back(strs[i]);
}
for(map<string,vector<string> >::iterator it=map_str.begin(); it!=map_str.end(); it++){
for(vector<string>::iterator it2 = it->second.begin(); it2!=it->second.end() &&(it->second).size()>1; it2++){
vec_str.push_back(*it2);
}
}
return vec_str;
}
};