46 ms C++ solution which beats 98.52% submissions


  • 0
    C
    class Solution {
    public:
        vector<vector<string>> groupAnagrams(vector<string>& strs) {
            vector<vector<string>> ret;
            unordered_map<string, int> loc;
            for (int i = 0; i < strs.size(); ++i) {
                string key=getHashKey(strs[i]);
                unordered_map<string, int>::iterator it=loc.find(key);
                if (it!=loc.end()) {
                    ret[it->second].push_back(strs[i]);
                }
                else {
                    loc[key]=ret.size();
                    vector<string> temp(1, strs[i]);
                    ret.push_back(temp);
                }
            }
            return ret;
        }
        private:
        string getHashKey(string& str) {
            string ret(26,0);
            for (int i=0; i<str.size(); ++i) {
                ++ret[str[i]-'a'];
            }
            return ret;
        }
    };
    

Log in to reply
 

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