64ms, >=95.80% C++ solution using a single hash map


  • 0
    J
    class Solution {
    
     public:
    
      vector<vector<string>> groupAnagrams(vector<string>& strs) {
         vector<vector<string>> res; 
         vector<string> tmp; 
         unordered_map<string,int> hash; 
        // if(strs.size()==0) res.push_back(tmp); 
         
         for(int i=0;i<strs.size();i++) { 
                 string stmp=strs[i]; 
                 sort(stmp.begin(),stmp.end()); 
    
                 if(hash.find(stmp)==hash.end()) { 
                        hash[stmp]=res.size();
                        res.push_back(tmp);
                        res[res.size()-1].push_back(strs[i]); 
                 }
                 else 
                    res[hash[stmp]].push_back(strs[i]);
         }
         for(int i=0;i<res.size();i++) sort(res[i].begin(),res[i].end());
         
         return res; 
     }
     };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.