44 ms c++ solution using hashing with prime numbers


  • 1
    P
    class Solution {
    public:
    vector<int> genPrime(int n) {
        vector<int> res;
        res.push_back(2);
        if (n==1) return res;
        int k = 1;
        for (int i = 3; k < n; i+=2) {
            int j = 2;
            int end = sqrt(i);
            bool prime = true;
            while(j <= end) {
                if (i%j==0) {
                    prime = false;
                    break;
                }
                j++;
            }
            if (prime) {
                k++;
                res.push_back(i);
            }
        }
        return res;
    }
        vector<string> anagrams(vector<string> &s) {
            int n = s.size();
            vector<string> res;
            if (n==0 || n==1) return res;
            vector<int> primes = genPrime(26);
            unordered_map<long, int> m;
            unordered_map<long, int>::iterator it;
            for (int i = 0; i < n; ++i) {
                long hash=1;
                for (int j = 0; j < s[i].size(); ++j) {
                    hash *= primes[s[i][j]-'a'];
                }
                it = m.find(hash);
                if (it == m.end()) {
                    m[hash] = i;
                } else {
                    if (it->second > -1) {
                        res.push_back(s[it->second]);
                        m[hash] = -1;
                    }
                    res.push_back(s[i]);
                }
            }
            return res;
        }
    };

  • 0

    Without any comment! Really bad habits to share!


Log in to reply
 

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