// 演算法 / Algorithm:
// 用兩張 unordered_map 維護「字母→單字」與「單字→字母」兩個方向的對應，
// 一邊用 istringstream 切詞一邊比對；任一方向衝突即 false，最後字數必須相等。
// Two unordered_maps track letter→word and word→letter; we split words with a
// stringstream and check both directions, requiring equal counts at the end.

#include <string>
#include <sstream>          // istringstream：方便用空格切詞 / split words by spaces
#include <unordered_map>    // 雜湊表 / hash maps

class Solution {
public:
    bool wordPattern(std::string pattern, std::string s) {
        // 兩張對應表 / the two mapping tables
        std::unordered_map<char, std::string> char2word; // 字母 → 單字 / letter → word
        std::unordered_map<std::string, char> word2char; // 單字 → 字母 / word → letter

        std::istringstream iss(s); // 把 s 包成可逐詞讀取的串流 / wrap s as a token stream
        std::string word;          // 暫存當前單字 / holds the current word
        size_t i = 0;              // 目前對到 pattern 的第幾個字母 / index into pattern

        // iss >> word 每次讀出一個以空白分隔的單字，讀完回傳 false 結束迴圈
        // `iss >> word` extracts one whitespace-separated word each loop.
        while (iss >> word) {
            if (i >= pattern.size()) return false; // 單字比字母多 / more words than letters
            char c = pattern[i];                   // 當前字母 / current letter

            // auto + find：在表中查 c；it == end() 代表「沒找到」
            // `find` returns an iterator; == end() means "not present".
            auto fw = char2word.find(c);
            if (fw != char2word.end()) {
                // 字母已對應過，必須是同一個單字 / letter mapped before → must match
                if (fw->second != word) return false; // fw->second 是對應的單字 / its word
            } else {
                // 字母是新的：確認單字未被別的字母佔用 / new letter → word must be free
                auto rv = word2char.find(word);
                if (rv != word2char.end()) {
                    // 單字已被某字母佔用，且不是 c → 衝突 / word owned by another letter
                    if (rv->second != c) return false;
                } else {
                    // 兩個方向都是全新，建立雙向對應 / brand-new pair → record both ways
                    char2word[c] = word;   // operator[] 不存在就插入 / insert forward
                    word2char[word] = c;   // 插入反向 / insert reverse
                }
            }
            ++i; // 換下一個字母 / advance to next letter
        }

        // 字母數必須等於單字數，否則字母比單字多 → false
        // Letters must equal words; leftover letters mean no full match.
        return i == pattern.size();
    }
};
