一、题目
二、思路
遍历strs,维护一个哈希表其中key是升序排列的字符串,value是一个vector<int>(Java是List<Integer>)集合,将每一个字符串排序后加入,排序字符串key,下标集合做value存入map,最后遍历map即可
class Solution {
public:
map<string, vector<int>> map; // 统计信息
vector<vector<string>> res; // 结果集合
void qsort(string& arr, int l, int r) { // 快排
if (l > r) return;
srand(time(0));
int i = l, s = l - 1, e = r + 1, x = arr[rand() % (r - l + 1) + l];
while (i < e)
if (arr[i] > x) swap(arr[i], arr[--e]);
else if (arr[i] < x) swap(arr[i++], arr[++s]);
else i++;
qsort(arr, l, s), qsort(arr, e, r);
}
vector<vector<string>> groupAnagrams(vector<string>& strs) {
for (int i = 0; i < strs.size(); i++) { // 遍历
string x = strs[i]; // 深拷贝
qsort(x, 0, x.size() - 1); // 按字母升序
if (map[x].size()) { // 如果该key对于的value中已经有其他下标
auto v = map[x]; // 取出来
v.push_back(i); // 再加进去
map[x] = v; // 重新加入map
}
else map[x] = {i}; // 如果没有就直接加入map
}
auto b = map.begin(), e = map.end(); // 遍历map
for (; b != e; b++) {
auto ans = b->second; // 拿出同一类异位词
vector<string> cow; // 存进去
for (auto x : ans)
cow.push_back(strs[x]);
res.push_back(cow); // 存进去
}
return res;
}
};