// 演算法 / Algorithm:
// 對每個字串把字元排序成「簽名」，用 unordered_map 以簽名為鍵收集字串。
// 最後把每個桶（bucket）搬進結果向量。
// Sort each string's chars into a signature; collect strings in an unordered_map
// keyed by signature; finally move each bucket into the result vector.

#include <vector>
#include <string>
#include <unordered_map>
#include <algorithm>   // std::sort

class Solution {
public:
    std::vector<std::vector<std::string>> groupAnagrams(std::vector<std::string>& strs) {
        // unordered_map：雜湊表，鍵=簽名，值=該簽名的字串清單
        // hash map: key = signature, value = list of strings with that signature.
        std::unordered_map<std::string, std::vector<std::string>> groups;

        // range-for：依序取出 strs 裡每個字串；const& 避免複製、且不修改原值
        // range-for over strs; const& avoids copying and forbids mutation.
        for (const std::string& s : strs) {
            std::string key = s;            // 複製一份當簽名來源 / copy to build the signature
            std::sort(key.begin(), key.end()); // 排序字元 → 簽名 / sort chars -> signature
            // groups[key] 若鍵不存在會自動建立空 vector，再 push_back 加入字串
            // operator[] auto-creates an empty vector if key is new, then we append.
            groups[key].push_back(s);
        }

        std::vector<std::vector<std::string>> result;   // 最終答案 / final answer
        result.reserve(groups.size());                  // 預留容量，減少重新配置 / reserve to avoid reallocs

        // 結構化綁定 [key, bucket]：把 map 的每個 pair 拆成鍵與值
        // structured binding splits each map entry into key and value.
        for (auto& [key, bucket] : groups) {
            // std::move：把 bucket 內容「搬」進結果，避免再複製一份字串
            // std::move transfers ownership instead of copying the vector.
            result.push_back(std::move(bucket));
        }
        return result;
    }
};
