// 演算法：滑動視窗 + 26 大小計數陣列。right 擴張，若某字元計數超過 2 就從左縮小，
// 每個合法視窗更新最大長度。時間 O(n)，空間 O(1)。
// Algorithm: sliding window with a 26-slot count array. Expand right; if any char
// exceeds 2, shrink from left; update the max valid window length. O(n) time, O(1) space.
int maximumLengthSubstring(char* s) {
    int cnt[26] = {0};          // 每個字母在視窗內的出現次數，初值全 0 / occurrences of each letter in the window, all zero
    int left = 0;               // 視窗左邊界 / left boundary of the window
    int ans = 0;                // 目前找到的最大合法長度 / best valid length so far

    // right 逐一掃過整個字串，作為視窗右邊界 / right scans the whole string as the window's right edge
    for (int right = 0; s[right] != '\0'; right++) {
        int c = s[right] - 'a';   // 把字元轉成 0..25 的索引（'a'→0, 'b'→1 …）/ map char to index 0..25
        cnt[c]++;                 // 新字元加入視窗，次數加一 / new char enters the window, bump its count

        // 若這個字元出現超過兩次，不斷從左移出直到修復不變量
        // While this char appears more than twice, drop chars from the left until fixed
        while (cnt[c] > 2) {
            cnt[s[left] - 'a']--; // 把最左字元移出視窗，其次數減一 / remove leftmost char, decrement its count
            left++;               // 左邊界右移一格 / advance the left boundary
        }

        // 現在視窗 [left, right] 合法，用它的長度更新答案
        // Window [left, right] is now valid; update answer with its length
        int len = right - left + 1;  // 視窗長度 / current window length
        if (len > ans) ans = len;    // 取較大者 / keep the larger
    }
    return ans;   // 回傳最大長度 / return the maximum length
}
