1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { unordered_map<string, vector<string>> m; for (string &s : strs) { m[strSort(s)].emplace_back(s); } vector<vector<string>> ans(m.size()); int i = 0; for (auto [_, s] : m) ans[i++] = move(s); return ans; } string strSort(string &s) { int cnt[26] = {0}; for (auto &c : s) ++cnt[c - 'a']; string ans; for (int i = 0; i < 26; i++) ans += string(cnt[i], i + 'a'); return ans; } };
|