fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4.  
  5. vector<vector<string>> groupAnagrams(vector<string> &str)
  6. {
  7. map<string, vector<string>> anagramGroupMap;
  8.  
  9. //Iterating for anagram strings
  10. for(auto st : str)
  11. {
  12. string sortedStr = st; //temp string
  13. sort(sortedStr.begin(), sortedStr.end());
  14. anagramGroupMap[sortedStr].push_back(st);
  15. }
  16.  
  17. vector<vector<string>> result;
  18.  
  19. //Store the grouped anagrams in a vector<vector<string>>
  20. for(auto &grp : anagramGroupMap)
  21. {
  22. result.push_back(grp.second);
  23. }
  24.  
  25. return result;
  26. }
  27.  
  28. int main()
  29. {
  30. vector<string> inputStr = {"eat","tea","tan","ate","nat","bat"};
  31. vector<vector<string>> ans = groupAnagrams(inputStr);
  32.  
  33. for(const auto &grp : ans)
  34. {
  35. cout <<"[ ";
  36. for(const string &ana : grp)
  37. {
  38. cout << ana << " ";
  39. }
  40. cout << " ]";
  41. }
  42.  
  43. return 0;
  44. }
Success #stdin #stdout 0.01s 5276KB
stdin
10
aba
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
stdout
[ bat  ][ eat tea ate  ][ tan nat  ]