Share my C++ solution 99.9 runtime beats


  • 0
    E

    101 / 101 test cases passed.
    Status: Accepted
    Runtime: 22 ms
    Submitted: 0 minutes ago

    Assign a prime number for a to z, and then multiply all prime numbers together to form a hash value.

    Code here

     
    class Solution {
        
    public:
        vector<vector<string>> groupAnagrams(vector<string>& strs) {
            vector<vector<string> > ans;
            if (strs.empty()) {
                return ans;
            }
            unordered_map<int, vector<string>> hash;
            vector<int> primes{2, 3, 5, 7, 11, 13, 17, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 107};
            for (const string& str : strs) {
                int getHash = 1;
                for (int i = 0; i < (int)str.size(); i++) {
                    getHash *= primes[str[i] - 'a'];
                }
                if (hash[getHash].size()) {
                    hash[getHash].push_back(str);
                } else {
                    hash[getHash] = vector<string>{str};
                }
            }
            for (const auto& hashList : hash) {
                if (hashList.second.size()) {
                    ans.push_back(hashList.second);
                }
            }
            return ans;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.