Leetcode 49. Group Anagrams (Medium) (cpp)
Tag: Hash Table, String
Difficulty: Medium
/*
49. Group Anagrams (Medium)
Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
Note: All inputs will be in lower-case.
*/
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> res;
vector<int> primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107};
unordered_map<long, int> mapping;
int pos = 0;
for (auto s : strs) {
long temp = 1;
if (s != "") {
for (auto cha : s) {
temp *= primes[cha - 'a'];
}
} else {
temp = 107;
}
if (mapping.find(temp) == mapping.end()) {
mapping[temp] = pos++;
res.push_back(vector<string>{s});
} else {
res[mapping[temp]].push_back(s);
}
}
return res;
}
};