Given an array of strings, group anagrams together.

Example:

Input: 
["eat", "tea", "tan", "ate", "nat", "bat"]
,
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]

Note:

  • All inputs will be in lowercase.
  • The order of your output does not matter.

题解:

直接对字符串排序,建立索引

class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> res;
int n = strs.size();
if (n == 0) {
return res;
}
vector<string> data(strs);
map<string, int> m;
int k = 0;
for (int i = 0; i < n; i++) {
sort(data[i].begin(), data[i].end());
if (m.find(data[i]) == m.end()) {
m.insert(make_pair(data[i], k));
vector<string> idx;
idx.push_back(strs[i]);
res.push_back(idx);
k++;
}
else {
res[m[data[i]]].push_back(strs[i]);
}
}
return res;
}
};