// 演算法 / Algorithm:
// 用長度 26 的計數陣列記錄 magazine 每個字母的數量，
// 再掃 ransomNote 逐一扣減；若某字母不夠用就回傳 false。
// Tally magazine's letters in a 26-slot array, then decrement per
// note letter; return false the moment a letter runs out.

#include <stdbool.h>   // 讓我們能用 bool / true / false / lets us use bool, true, false

bool canConstruct(char* ransomNote, char* magazine) {
    int count[26] = {0};                  // 26 個字母的計數，全部初始化為 0 / counts for 26 letters, all zeroed
                                          // {0} 會把整個陣列填 0 / {0} zero-initializes the whole array

    // 第一遍：統計 magazine 裡每個字母出現幾次 / Pass 1: count each letter in magazine
    for (int i = 0; magazine[i] != '\0'; i++) {   // C 字串以 '\0' 結尾，遇到它就停 / C strings end at '\0'
        count[magazine[i] - 'a']++;       // magazine[i]-'a' 把字母轉成 0..25 的索引 / map letter to index 0..25
    }                                     // ++ 表示該字母數量加一 / ++ adds one to that letter's tally

    // 第二遍：掃 ransomNote，逐一檢查並扣減 / Pass 2: walk the note, check then decrement
    for (int i = 0; ransomNote[i] != '\0'; i++) {
        int idx = ransomNote[i] - 'a';    // 算出這個字母對應的索引 / index for this needed letter
        if (count[idx] == 0) {            // 已經沒有這個字母可用了 / no copies of this letter left
            return false;                 // 無法拼出，立即回傳 false / can't build it, return false now
        }
        count[idx]--;                     // 用掉一個，數量減一 / consume one copy, decrement
    }

    return true;                          // 全部字母都湊齊了 / every needed letter was available
}
