share my c++ solution, 29ms, simple and straightforward


  • 0
    S

    idea is simple, sort the string and put in a hash map with the sorted string as the key, and the vector of string as the second

    class Solution {
    public:
        vector<vector<string>> groupAnagrams(vector<string>& strs) {
            //we can sort the string and put it in a map
            unordered_map<string,vector<string>> mp;
            for(int i=0;i<strs.size();i++)
            {
                string s=strs[i];
                sort(s.begin(),s.end());
                mp[s].push_back(strs[i]);
            }
            vector<vector<string>> res;
            for(auto it=mp.begin();it!=mp.end();it++)
            {
                res.push_back(it->second);
            }
            return res;
        }
    };
    

Log in to reply
 

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