// 演算法 / Algorithm:
// 用長度 26 的計數陣列統計 magazine 的字母，
// 再掃 ransomNote 逐一扣減；任何字母不夠就回傳 false。
// Tally magazine's letters in a 26-slot array, then decrement per
// note letter; return false as soon as one runs out.

#include <string>
#include <array>
using namespace std;

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        // std::array<int,26> 是固定大小陣列，{} 把元素全設為 0
        // std::array<int,26> is a fixed-size array; {} zero-initializes every element
        array<int, 26> count{};

        // range-for：依序取出 magazine 的每個字元 c（char 型別）
        // range-for: iterate over each character c of magazine
        for (char c : magazine) {
            count[c - 'a']++;             // c-'a' 轉成 0..25 索引，該字母計數加一 / map to 0..25, increment
        }

        // 掃 ransomNote，每個字母先檢查再扣減 / scan the note, check before decrementing
        for (char c : ransomNote) {
            int idx = c - 'a';            // 這個字母對應的索引 / index of this needed letter
            if (count[idx] == 0) {        // 沒有剩餘的這個字母 / none of this letter remain
                return false;             // 拼不出來 / cannot construct
            }
            count[idx]--;                 // 用掉一個 / consume one copy
        }

        return true;                      // 所有字母都夠 / all letters were available
    }
};
