C++ | Leetcode C++题解之第49题字母异位词分组

题目:

题解:

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        // 自定义对 array<int, 26> 类型的哈希函数
        auto arrayHash = [fn = hash<int>{}] (const array<int, 26>& arr) -> size_t {
            return accumulate(arr.begin(), arr.end(), 0u, [&](size_t acc, int num) {
                return (acc << 1) ^ fn(num);
            });
        };

        unordered_map<array<int, 26>, vector<string>, decltype(arrayHash)> mp(0, arrayHash);
        for (string& str: strs) {
            array<int, 26> counts{};
            int length = str.length();
            for (int i = 0; i < length; ++i) {
                counts[str[i] - 'a'] ++;
            }
            mp[counts].emplace_back(str);
        }
        vector<vector<string>> ans;
        for (auto it = mp.begin(); it != mp.end(); ++it) {
            ans.emplace_back(it->second);
        }
        return ans;
    }
};

相关推荐

  1. leetcode49字母分组

    2024-04-26 16:24:05       46 阅读
  2. 【算法49. 字母分组

    2024-04-26 16:24:05       57 阅读
  3. [ LeetCode ] 刷刷(Python)-49字母分组

    2024-04-26 16:24:05       35 阅读
  4. LeetCode 49 字母分组

    2024-04-26 16:24:05       63 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-26 16:24:05       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-26 16:24:05       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-26 16:24:05       82 阅读
  4. Python语言-面向对象

    2024-04-26 16:24:05       91 阅读

热门阅读

  1. 用Python创建日历详细指南

    2024-04-26 16:24:05       30 阅读
  2. HOT100与剑指Offer

    2024-04-26 16:24:05       34 阅读
  3. 终端安全加强

    2024-04-26 16:24:05       34 阅读
  4. RSV——calculate_rmsd计算Rmsd

    2024-04-26 16:24:05       31 阅读
  5. 银联云闪付扫码支付通道接口如何申请?

    2024-04-26 16:24:05       30 阅读
  6. C语言-单片机:STM32程序烧录的几种方法

    2024-04-26 16:24:05       31 阅读
  7. macbook m1 nacos集群启动失败报错的解决办法

    2024-04-26 16:24:05       33 阅读
  8. vue 根据url预览或下载文件

    2024-04-26 16:24:05       36 阅读
  9. 国内大模型五虎

    2024-04-26 16:24:05       32 阅读