Anagrams
时间:2014-06-04 19:26:02
收藏:0
阅读:334
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
class Solution {
public:
vector<string> anagrams(vector<string> &strs)
{
vector<string> result;
map<string,int> mapindex;
for(int i=0;i<strs.size();i++)
{
string str=strs[i];
sort(str.begin(),str.end());
if(mapindex.find(str)==mapindex.end())
mapindex[str]=i;
else
{
if(mapindex[str]>-1)
{
result.push_back(strs[mapindex[str]]);
mapindex[str]=-1;
}
result.push_back(strs[i]);
}
}
return result;
}
};
public:
vector<string> anagrams(vector<string> &strs)
{
vector<string> result;
map<string,int> mapindex;
for(int i=0;i<strs.size();i++)
{
string str=strs[i];
sort(str.begin(),str.end());
if(mapindex.find(str)==mapindex.end())
mapindex[str]=i;
else
{
if(mapindex[str]>-1)
{
result.push_back(strs[mapindex[str]]);
mapindex[str]=-1;
}
result.push_back(strs[i]);
}
}
return result;
}
};
原文:http://www.cnblogs.com/erictanghu/p/3759378.html
评论(0)