cpp: add «49. Group Anagrams»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-02-06 10:59:37 +01:00
parent e12d5fafdb
commit 93ef2e6198
No account linked to committer's email address

26
cpp/group-anagrams.cpp Normal file
View file

@ -0,0 +1,26 @@
#include <algorithm>
#include <string>
#include <unordered_map>
#include <vector>
class Solution {
using words_t = std::vector<std::string>;
public:
std::vector<words_t> groupAnagrams(const words_t &strs) {
std::unordered_map<std::string, words_t> groups;
for (const auto &s : strs) {
std::string sorted_s = s;
std::sort(sorted_s.begin(), sorted_s.end());
groups[sorted_s].push_back(s);
}
std::vector<words_t> result;
for (const auto [_, words] : groups) {
result.push_back(std::move(words));
}
return result;
}
};