Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
1:注意特殊情况;2:anagrams是组成单词的字母种类和个数都相同;3:遍历数组,对每一个单词进行按升序排序,检测当前排序后的字符串是否在map中,如果存在以及不存在两种处理方法。
vector<string> anagrams(vector<string> &strs)
{
if(strs.size() == 0)
{
return strs;
}
vector<string> result;
unordered_map<string, int> myMap;
for(int i = 0; i < (int)strs.size(); i++)
{
string tmp = strs[i];
sort(tmp.begin(), tmp.end());
if(myMap.find(tmp) == myMap.end())
{
myMap[tmp] = i;
}
else
{
if(myMap[tmp] == -1)
{
result.push_back(strs[i]);
}
else
{
result.push_back(strs[myMap[tmp]]);
myMap[tmp] = -1;
result.push_back(strs[i]);
}
}
}
return result;
}