Compact C++ solution using unordered_map and multiset


  • 3
    K
    class Solution {
    public:
        vector<vector<string>> groupAnagrams(vector<string>& strs) {
            unordered_map<string, multiset<string>> table;
            for (auto it = strs.begin(); it != strs.end(); ++it) {
                string key(*it);
                sort(key.begin(), key.end());
                table[key].insert(*it);
            }
            
            vector<vector<string>> result;
            for (auto it = table.begin(); it != table.end(); ++it)
                result.push_back(vector<string>(it->second.begin(), it->second.end()));
            return result;
        }
    };

  • 0
    A

    combination of some good answers:

    class Solution {
    public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
    vector<vector<string>> res;
    vector<string> sortedstrs(strs);
    unordered_map<string, multiset<string>> mp;
    for (int i = 0; i < strs.size(); ++i){
    sort(sortedstrs[i].begin(), sortedstrs[i].end());
    mp[sortedstrs[i]].emplace(strs[i]);
    }

        for (auto it = mp.begin(); it != mp.end(); ++it){
            res.emplace_back(it->second.begin(), it->second.end());
        }
        return res;
    }
    

    };


Log in to reply
 

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