| 12 | using namespace std; |
| 13 | |
| 14 | class Solution { |
| 15 | private: |
| 16 | unsigned long prime = 51; |
| 17 | |
| 18 | public: |
| 19 | vector<vector<string>> groupAnagrams(vector<string>& strs) { |
| 20 | vector<unsigned long> hash; |
| 21 | vector<vector<string>> res; |
| 22 | for (string str : strs) { |
| 23 | unsigned s_hash = getHash(str); |
| 24 | bool found = false; |
| 25 | for (int i = 0; i < hash.size(); i ++) { |
| 26 | if (hash[i] == s_hash) { |
| 27 | res[i].push_back(str); |
| 28 | found = true; |
| 29 | break; |
| 30 | } |
| 31 | } |
| 32 | if (not found) { |
| 33 | hash.push_back(s_hash); |
| 34 | res.push_back({str}); |
| 35 | } |
| 36 | } |
| 37 | return res; |
| 38 | } |
| 39 | |
| 40 | unsigned long getHash(string str) { |
| 41 | int cnt[26] = {0}; |
| 42 | for (char c : str) { |
| 43 | cnt[c - 'a'] ++ ; |
| 44 | } |
| 45 | unsigned long res = 0; |
| 46 | for (int i = 0; i < 26; i++) { |
| 47 | res += cnt[i] * pow(prime, i); |
| 48 | } |
| 49 | return res; |
| 50 | } |
| 51 | |
| 52 | |
| 53 | // O(1) |
| 54 | unsigned long pow(unsigned long x, unsigned int y) { |
| 55 | // bitwise traverse y |
| 56 | unsigned long res = 1; |
| 57 | for (int offset = sizeof(int) * 8 - 1; offset >= 0; offset --) { |
| 58 | res *= res; // right shift |
| 59 | if (y & (1 << offset)) res *= x; |
| 60 | } |
| 61 | return res; |
| 62 | } |
| 63 | }; |
| 64 | |
| 65 | int main() { |
| 66 | Solution a; |
nothing calls this directly
no outgoing calls
no test coverage detected