题目:Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
查了半天才搞懂意思,anagrams的意思是几个单词,如果每种字母出现的个数都相同,不考虑顺序,那么他们就是一类的。
输出所有是一类的单词,anagram【s】 所以如果一个单词和其他单词都不是一类的,那就不输出了。
我理解的anagrams的判别其实就是,把输入的单词按字母顺序排序,如果排序后是同一字典序,那么他们就是一类的。
做法就是用map存第一个出现的单词排序后的值和他在strs数组中的index,之后每遇到一个单词,处理后判断怎么对map操作和是否输出。
要注意的就是map匹配后要先考虑map中存的单词是否输出,如果没有就输出并吧index赋值成-1表示输出过。
class Solution {
public:
vector<string> anagrams(vector<string> &strs) {
map<string,int> m;
vector<string> result;
int len=strs.size();
for(int i=0;i<len;++i)
{
string a=strs[i];
sort(a.begin(),a.end());
if(m.find(a)==m.end())
{
m[a]=i;
}
else
{
int index=m[a];
if(index>=0)
{
result.push_back(strs[index]);
m[a]=-1;
}
result.push_back(strs[i]);
}
}
return result;
}
};