Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
首先搞清楚什么是anagrams,英文的回文,只要组成这些单词用的字母个数和类型相同就是回文。
class Solution {
public:
vector<string> anagrams(vector<string> &strs) {
vector<string> results;
map<string, int> anagramsMap;
for(int ii = 0; ii < strs.size(); ii ++) {
string temp = strs[ii];
sort(temp.begin(), temp.end());
if(anagramsMap.find(temp) == anagramsMap.end()) {
anagramsMap[temp] = ii;
}
else {
if(anagramsMap[temp] >= 0) { // This is the second time this string appears, put the first one into the result.
results.push_back(strs[anagramsMap[temp]]);
anagramsMap[temp] = -1;
}
results.push_back(strs[ii]);
}
}
return results;
}
};