Advertisement
vaibhav1906

Group Anagrams

Nov 22nd, 2021
1,393
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.88 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<vector<string>> groupAnagrams(vector<string>& strs) {
  4.        
  5.         unordered_map<string, vector<string>> m;
  6.        
  7.         for(int i = 0; i<strs.size(); i++){
  8.             string temp = strs[i];
  9.             sort(temp.begin(), temp.end());
  10.             if(m.find(temp)==m.end()){
  11.                 vector<string> xyz = {strs[i]};
  12.                 m.insert({temp,xyz});
  13.                 //m.insert({temp,{strs[i]}}); => sort way
  14.             }
  15.             else{
  16.                 vector<string> v = m.find(temp)->second;
  17.                 v.push_back(strs[i]);
  18.                 m.find(temp)->second = v;
  19.             }
  20.            
  21.         }
  22.        
  23.         vector<vector<string>> ans;
  24.        
  25.         for(auto it = m.begin(); it!=m.end(); it++){
  26.             ans.push_back(it->second);
  27.         }
  28.        
  29.        
  30.         return ans;
  31.     }
  32. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement