Cpp solution with vector, set and pointers


  • 0
    S

    '''
    class Solution {
    public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {

        unordered_map<string, vector<int>> counter;
        vector<vector<string>> result;
        int ctr = 0;
        for (string s: strs)
        {
            
            sort(s.begin(),s.end());
            
            if (counter.find(s) != counter.end())
            {
                 vector<int> *result = &counter.find(s)->second;
                 result->push_back(ctr);
                
            }
            else
            {
                vector<int> *result = new vector<int> ;
                result->push_back(ctr);
                counter.insert(std::pair<string,vector<int>>(s,*result));
            }
            ctr++;
    
        }
        
        
        for( auto i : counter)
        {
            
            vector<string> temp_result;
            for (auto idx : i.second)
            {
               
                temp_result.push_back(strs[idx]);
            }
            result.push_back(temp_result);
        }
        return result;
        
        
        
    }
    

    };

    '''


Log in to reply
 

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