c++ solution with hashtable and countsort beats 98%


  • 0
    K
    class Solution {
    public:
        string count_sort(string str)
        {
            vector<int> table(26, 0);
            for(auto c : str)
            {
                table[c - 'a']++;
            }
            string res = "";
            for(int i = 0; i < table.size(); ++i)
            {
                while(table[i] > 0)
                {
                    res += char('a' + i);
                    table[i]--;
                }
            }
            return res;
        }
        vector<vector<string>> groupAnagrams(vector<string>& strs) {
            unordered_map<string,vector<string>> hashtable;
            vector<vector<string>> res;
            for(auto str : strs)
            {
                string key = count_sort(str);
                hashtable[key].push_back(str);
            }
            for(auto i : hashtable)
            {    
                res.push_back(i.second);
            }
            return res;
        }
    };

Log in to reply
 

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