fork download
  1. // C++ Code to group anagrams together by using frequency
  2. // as keys
  3.  
  4. #include <bits/stdc++.h>
  5. using namespace std;
  6.  
  7. const int MAX_CHAR = 26;
  8.  
  9. // function to generate hash of word s
  10. string getHash(string &s) {
  11. string hash;
  12. vector<int> freq(MAX_CHAR, 0);
  13.  
  14. // Count frequency of each character
  15. for(char ch: s)
  16. freq[ch - 'a'] += 1;
  17.  
  18. // Append the frequency to construct the hash
  19. for(int i = 0; i < MAX_CHAR; i++) {
  20. hash.append(to_string(freq[i]));
  21. hash.append("$");
  22. }
  23.  
  24. return hash;
  25. }
  26.  
  27. vector<vector<string>> anagrams(vector<string> &arr) {
  28. vector<vector<string>> res;
  29. unordered_map<string, int> mp;
  30. for (int i = 0; i < arr.size(); i++) {
  31. string key = getHash(arr[i]);
  32.  
  33. // If key is not present in the hash map, add
  34. // an empty group (vector) in the result and
  35. // store the index of the group in hash map
  36. if (mp.find(key) == mp.end()) {
  37. mp[key] = res.size();
  38. res.push_back({});
  39. }
  40.  
  41. // Insert the string in its correct group
  42. res[mp[key]].push_back(arr[i]);
  43. }
  44. return res;
  45. }
  46.  
  47. int main() {
  48. vector<string> arr = {"act", "god", "cat", "dog", "tac"};
  49.  
  50. vector<vector<string>> res = anagrams(arr);
  51. for(int i = 0; i < res.size(); i++) {
  52. for(int j = 0; j < res[i].size(); j++)
  53. cout << res[i][j] << " ";
  54. cout << "\n";
  55. }
  56. return 0;
  57. }
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
act cat tac 
god dog