diff --git a/cpp/2210/221028.cpp b/cpp/2210/221028.cpp new file mode 100644 index 0000000..f5ea5ca --- /dev/null +++ b/cpp/2210/221028.cpp @@ -0,0 +1,38 @@ +#include +#include +#include + +/** + * 49. Group Anagrams + * + * Given an array of strings strs, group the anagrams together. You can return the answer in any order. + * An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. + */ + +class Solution { +private: + static inline long long h(const std::string& s) { + long long ret = 0; + int pos; + for (char c : s) { + pos = (c - 'a') << 1; + ret = (ret & ~(3LL << pos)) | (((ret >> pos & 3) + 1) & 3) << pos; + } + return ret | s.length() << 52; + } + +public: + static std::vector> groupAnagrams(const std::vector& strs) { + std::unordered_map*> m; + for (const std::string& s : strs) { + auto hash = h(s); + if (!m.count(hash)) + m[hash] = new std::vector; + m[hash]->push_back(s); + } + std::vector> ret; + for (const auto& [hash, ptr] : m) + ret.push_back(std::move(*ptr)); + return ret; + } +}; diff --git a/cpp/2210/CMakeLists.txt b/cpp/2210/CMakeLists.txt index 2bc0125..e7d9982 100644 --- a/cpp/2210/CMakeLists.txt +++ b/cpp/2210/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2210) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2210 221027-CN.cpp) +ADD_EXECUTABLE(2210 221028.cpp)