c++ solution using map (49ms)


  • 1
    H
    class Solution {
    public:
        vector<vector<string>> groupAnagrams(vector<string>& strs) {
            
            vector<vector<string>> ret;
            map<vector<int>, int> map;
            int index = 0;
            
            for(int i = 0; i < strs.size(); i++) {
                vector<int> hmap(26, 0);
                for(int j = 0; j < strs[i].size(); j++) {
                    hmap[strs[i][j] - 'a']++;
                }
                
                if (map.find(hmap) == map.end()) {
                    map[hmap] = index;
                    ret.push_back(vector<string>());
                    index++;
                }
                
                ret[map[hmap]].push_back(strs[i]);
            }
            
            return ret;
        }
    };
    

  • 1
    H

    Slightly optimized version (46ms)

    class Solution {
    public:
        vector<vector<string>> groupAnagrams(vector<string>& strs) {
            
            vector<vector<string>> ret;
            map<vector<int>, int> map;
            int index = 0;
            
            for(int i = 0; i < strs.size(); i++) {
                vector<int> hmap(26, 0);
                for(int j = 0; j < strs[i].size(); j++) {
                    hmap[strs[i][j] - 'a']++;
                }
                
                if (map.find(hmap) == map.end()) {
                    map[hmap] = index;
                    ret.push_back(vector<string>());
                    ret[index].push_back(strs[i]);
                    index++;
                }
                
                else ret[map[hmap]].push_back(strs[i]);
            }
            
            return ret;
        }
    };
    

Log in to reply
 

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