17 lines, 69ms, straightforward C++ solution with unordered_map


  • 0
    Y
    class Solution {
    public:
        vector<vector<string>> groupAnagrams(vector<string>& strs) {
            vector<vector<string>> reval;
            unordered_map<string, int> mapper;
            for(const std::string & str : strs){
                std::string key(str);
                std::sort(key.begin(),key.end());
                if(mapper.find(key)==mapper.end()){
                    reval.push_back(vector<string>());//add new vector
                    mapper[key] = reval.size()-1;//store the related index
                } 
                reval[mapper[key]].push_back(str);
            }
            return reval;
        }
    };
    

Log in to reply
 

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