1. 定义一个二维动态数组result,用于存储最终分组后的字符串数组。
vector<vector<string>> result;
2. 定义一个unordered_map,用于存储每个字符串排序后的结果以及对应的原字符串数组。
unordered_map<string, vector<string>> map;
3. 遍历输入的字符串数组strs。
for (const string& str : strs) {
4. 对每个字符串进行排序,得到排序后的字符串sortedStr。
string sortedStr = str;
sort(sortedStr.begin(), sortedStr.end());
5. 将原字符串str与排序后的字符串sortedStr作为键值对存入unordered_map中,对应的值为其在result中的下标。
map[sortedStr].push_back(str);
6. 遍历unordered_map,将每个键值对对应的值(原字符串数组)存入result中。
for (const auto& item : map) {
result.push_back(item.second);
}
7. 返回result。
完整代码:
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> result; unordered_map<string, vector<string>> map;
for (const string& str : strs) {
string sortedStr = str;
sort(sortedStr.begin(), sortedStr.end());
map[sortedStr].push_back(str);
}
for (const auto& item : map) {
result.push_back(item.second);
}
return result;
}
};