Group Anagrams
Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
Return:
[ ["ate", "eat","tea"], ["nat","tan"], ["bat"] ]
Note: All inputs will be in lower-case.
解题方法:
该题的要求是将同构词(由相同字母组成的词)进行归类,可以利用哈希思想进行处理。
代码:
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
vector< vector<string> > groupAnagrams(vector<string>& strs)
{
vector< vector<string> > res;
map<string, vector<string> > mp;
if(strs.empty()) return res;
for(int i = 0; i < strs.size(); i ++)
{
string str = strs[i];
sort(str.begin(),str.end());
mp[str].push_back(strs[i]);
}
for(map<string, vector<string> >::iterator it = mp.begin(); it != mp.end(); it ++)
{
res.push_back(it->second);
}
return res;
}
int main()
{
vector<string> strs;
vector< vector<string> > res;
string str;
while(cin>>str)
{
strs.push_back(str);
}
res = groupAnagrams(strs);
for(int i = 0 ; i < res.size(); i++)
{
for(int j =0; j < res[i].size(); j ++)
cout<<res[i][j]<<' ';
cout<<endl;
}
}