mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-10 00:09:06 +01:00
cpp: add «49. Group Anagrams»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
e12d5fafdb
commit
93ef2e6198
1 changed files with 26 additions and 0 deletions
26
cpp/group-anagrams.cpp
Normal file
26
cpp/group-anagrams.cpp
Normal 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;
|
||||||
|
}
|
||||||
|
};
|
Loading…
Reference in a new issue