From d3ca8e780ab0879cf8ffd5d44c5664ae8ad4f7ff Mon Sep 17 00:00:00 2001 From: liubang Date: Mon, 7 Oct 2024 11:41:41 +0800 Subject: [PATCH] update --- src/49.group-anagrams.cc | 63 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 src/49.group-anagrams.cc diff --git a/src/49.group-anagrams.cc b/src/49.group-anagrams.cc new file mode 100644 index 00000000..f9cf1aeb --- /dev/null +++ b/src/49.group-anagrams.cc @@ -0,0 +1,63 @@ +// Copyright (c) 2024 The Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Authors: liubang (it.liubang@gmail.com) + +#include + +#include +#include +#include +#include + +namespace { +class Solution { +public: + std::vector> groupAnagrams(const std::vector& strs) { + std::unordered_map> map; + for (const auto& str : strs) { + if (str.empty()) { + map[str].push_back(str); + } else { + std::string copy = str; + std::sort(copy.begin(), copy.end()); + map[copy].push_back(str); + } + } + std::vector> result; + result.reserve(map.size()); + for (const auto& [k, v] : map) { + result.emplace_back(v); + } + return result; + } +}; +} // namespace + +TEST(Leetcode, group_anagrams) { + Solution s; + { + std::vector> exp = { + {"bat"}, {"tan", "nat"}, {"eat", "tea", "ate"}}; + EXPECT_EQ(exp, s.groupAnagrams({"eat", "tea", "tan", "ate", "nat", "bat"})); + } + { + std::vector> exp = {{""}}; + EXPECT_EQ(exp, s.groupAnagrams({""})); + } + { + std::vector> exp = {{"a"}}; + EXPECT_EQ(exp, s.groupAnagrams({"a"})); + } +}