// 演算法 / Algorithm:
// 與 C 版相同：一次掃描記錄每個字母的「最後小寫索引」與「第一大寫索引」，
// Same as the C version: one pass records each letter's last-lowercase and
// first-uppercase index, then count letters where lastLower < firstUpper.

class Solution {
public:
    int numberOfSpecialChars(string word) {
        // vector<int> 是會自動管理記憶體的動態陣列；這裡固定 26 格，初值 -1
        // vector<int> is a dynamic array that manages its own memory; size 26, init -1
        vector<int> lastLower(26, -1);   // 每字母最後一次小寫的索引 / last lowercase index
        vector<int> firstUpper(26, -1);  // 每字母第一次大寫的索引 / first uppercase index

        // range-for：依序取出 word 中每個字元；i 同步追蹤索引
        // range-for iterates each char of word; i tracks the index in parallel
        for (int i = 0; i < (int)word.size(); i++) {
            char c = word[i];  // 目前字元 / current character
            if (islower(c)) {
                // islower：標準函式，判斷是否小寫；c - 'a' 映射成 0..25 的索引
                // islower: standard function testing lowercase; c - 'a' maps to 0..25
                lastLower[c - 'a'] = i;        // 覆蓋以保留最後一次 / keep the last one
            } else {
                // 只在尚未記錄（-1）時寫入，保留第一次大寫位置
                // Write only if not recorded yet (-1) to keep the first uppercase
                if (firstUpper[c - 'A'] == -1)
                    firstUpper[c - 'A'] = i;
            }
        }

        int count = 0;  // 特殊字母數量 / count of special letters
        for (int k = 0; k < 26; k++) {
            // 兩者皆出現且最後小寫早於第一大寫 → special
            // both exist AND last lowercase precedes first uppercase → special
            if (lastLower[k] != -1 && firstUpper[k] != -1 && lastLower[k] < firstUpper[k])
                count++;
        }
        return count;  // 回傳結果 / return the answer
    }
};
