这题我感觉不难,主要是对stl里面的map, vector, string要比较熟。
我的解法就是对每个输入的字符串,生成一个map,记录每个字母的count。然后比较有哪些字符串的map一样,如果一样就放到一个vector<string>里面 ,否则另起一个。不知道有没有更优的解法。
注意的地方有:
1) map_compare的写法。
#include <iostream>
#include <string>
#include <vector>
#include <map>
using namespace std;
bool map_compare(map<char,int> const &lhs, map<char, int> const &rhs) {
return lhs.size()==rhs.size() && equal(lhs.begin(), lhs.end(), rhs.begin());
}
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string> > sol;
if (strs.size()==0) return sol;
vector<map<char, int> > maps;
maps.resize(strs.size());
for (size_t i=0; i<strs.size(); ++i) {
vector<map<char, int> > m;
for (size_t j=0; j<strs[i].size(); ++j) {
maps[i][strs[i].at(j)]++;
}
}
vector<bool> tokens(strs.size(), 0);
for (size_t i=0; i<maps.size(); ++i) {
if (!tokens[i]) {
vector<string> tmp;
tmp.push_back(strs[i]);
for (size_t j=i+1; j<maps.size(); ++j) {
if (map_compare(maps[i], maps[j])) {
tmp.push_back(strs[j]);
tokens[j]=1;
}
}
sol.push_back(tmp);
}
}
return sol;
}
int main()
{
vector<string> inputStrs;
inputStrs.push_back("eat");
inputStrs.push_back("tea");
inputStrs.push_back("tan");
inputStrs.push_back("ate");
inputStrs.push_back("nat");
inputStrs.push_back("bat");
vector<vector<string> > sol;
sol = groupAnagrams(inputStrs);
cout<<"["<<endl;
for (auto i=sol.begin(); i<sol.end(); ++i) {
cout<<" [ ";
for (auto j=i->begin(); j<i->end(); ++j) {
cout<<(*j)<<" ";
}
cout<<"]"<<endl;
}
cout<<"]"<<endl;
return 0;
}