题干
解法一:
实在想不出hash的索引如何表达 瞄了一眼题解 对每一个string进行std::sort可以保持一致 作为hash索引
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
std::vector<std::vector<string>> res;
std::unordered_map<string, std::vector<string>> hash;
for (auto& str : strs) {
std::string sortedStr = str;
std::sort(sortedStr.begin(), sortedStr.end());
hash[sortedStr].push_back(str);
}
for(auto& entry : hash){
//res.push_back(entry.second);
res.push_back(std::move(entry.second));
}
return res;
}
};
此外强调一些内容
std::vector<任意> nums;
std::sort(nums.begin(), nums.end()) //一定要复制为一位数组
//此外循环使用
for(auto& x : nums)
//对于nums中的每一个元素引用调用
for(const auto& x : nums)
//这样避免nums中的元素被修改
for (auto& entry : hash) {
res.push_back(entry.second); // 拷贝 entry.second
}
/*这里使用的是 push_back(entry.second)。
entry.second 是一个 vector<string>。
所以这个写法会将 entry.second 拷贝 一份放入 res 中。
如果这个 vector 很大,会发生一次深拷贝,性能会差一些。*/
for (auto& entry : hash) {
res.push_back(std::move(entry.second)); // 移动 entry.second
}
/*std::move(entry.second) 把 entry.second 转换为右值。
push_back 会调用 vector<string> 的 移动构造函数,把内容“搬”进 res,不需要复制。
原来的 entry.second 会被“清空”,但这无所谓,因为我们用完就要丢掉。*/