leetcode 字母异位词分组 中等

时间:2021-08-08
本文章向大家介绍leetcode 字母异位词分组 中等,主要包括leetcode 字母异位词分组 中等使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

hash:把 a 当做 26^0,b 当做 26^1,就这样。

或者,根本不hash成数字,直接当各个字母频次当成 string 处理 (频次就成了对应的字符,如 '9' + 1 再就是 ':')。

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        if(strs.empty()) return {{""}};
        init();
        unordered_map<ull, vector<string>> map;
        for(int i = 0; i < strs.size(); ++ i) {
            ull temp = 0;
            for(int j = 0; j < strs[i].size(); ++ j) {
                temp += base[strs[i][j] - 'a'];
            }
            map[temp].emplace_back(strs[i]);
        }
        vector<vector<string>> ret;
        for(auto &item : map) ret.emplace_back(std::move(item.second));
        return ret;
    }
    
    void init() {
        for(int i = 0; i < 26; ++ i) {
            if(i == 0) base[i] = 1;
            else base[i] = base[i - 1] * 26 % mod;
        }
    }

    typedef unsigned long long ull;
    ull mod = 1e9 + 7;
    ull base[26];
};

原文地址:https://www.cnblogs.com/rookie-acmer/p/15114420.html