//思路差不多,有比较简洁的写法(第二种)
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
int N = strs.size(), index=0;
vector<vector<string>> res;
vector<string> temp;
map<string, int> dict;
string sorted_str;
for (int i = 0; i < N; i++) {
sorted_str = strs[i];
sort(sorted_str.begin(), sorted_str.end());
if (dict.find(sorted_str) == dict.end()) {
dict.insert(make_pair(sorted_str, index++));
temp.push_back(strs[i]);
res.push_back(temp);
temp.clear();
}
else {
res[dict[sorted_str]].push_back(strs[i]);
}
}
return res;
}
};
int main()
{
Solution sol;
vector<string> strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
vector<vector<string>> res = sol.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;
}
cout<< endl;
return 0;
}
//以下是简洁写法
(找不着了,大概是建立顺序字符串到同构字符串的dict,最后循环存储所有value,这样就不需要一个一个存,直接存的就是vector)