59ms C++ Solution


  • 0
    L
    typedef array<int, 26> Category;
    
    void getCategory(Category& result, const string& s) {
        result.fill(0);
        for (char c: s) {
            result[c - 'a']++;
        }
    }
    
    class Solution {
    public:
        vector<vector<string>> groupAnagrams(vector<string>& strs) {
            map<Category, vector<int>> group;
            Category category;
            int size = strs.size();
            for (int i = 0; i < size; i++) {
                getCategory(category, strs[i]);
                group[category].push_back(i);
            }
            vector<vector<string>> result;
            result.reserve(group.size());
            for (auto& c: group) {
                auto& v = *result.insert(result.end(), vector<string>());
                for (int idx: c.second) {
                    v.push_back(strs[idx]);
                }
            }
            return result;
        }
    };
    

Log in to reply
 

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