49. Group Anagrams

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        unordered_map<string, vector<string>> groups;
        for (string str:strs)
            groups[customedSort(str)].push_back(str);
        vector<vector<string>> res;

        for (auto kv:groups)
            res.push_back(kv.second);

        return res;
    }
private:
    //not using sort as it cost lenloglen
    string customedSort(string s) {
        vector<int> cnt(26, 0);
        for (int i = 0; i < s.size(); i++)
            cnt[s[i] - 'a']++;
        string sorted;
        for (int i = 0; i < 26; i++)
            for (int j = 0; j < cnt[i]; j++)
                sorted += i + 'a';
        return sorted;
    }

};

results matching ""

    No results matching ""