c++ O(mn) solution without sort


  • 0
    H
    class Solution {
    public:
        vector<vector<string>> groupAnagrams(vector<string>& strs) {
            vector<vector<string> > ans;
            int n = strs.size();
            if(!n) return ans;
            unordered_map<string, vector<string>> um;
            for(int i = 0; i < n; i ++) {
                string str(26, 0);
                for(int j = 0; j < strs[i].size(); j ++) str[strs[i][j]-'a']++;
                um[str].push_back(strs[i]);
            }
            for(auto iter = um.begin(); iter != um.end(); iter ++) 
                ans.push_back(iter->second);
            return ans;
        }
    };
    

Log in to reply
 

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