// 演算法同 C 版：滑動視窗維持「每字元 ≤ 2 次」的不變量，用 array<int,26> 計數。
// 時間 O(n)，空間 O(1)。
// Same as the C version: a sliding window keeping the "each char ≤ 2" invariant,
// counting with array<int,26>. O(n) time, O(1) space.
class Solution {
public:
    int maximumLengthSubstring(string s) {
        array<int, 26> cnt{};     // 固定 26 格計數陣列，{} 使全部初始化為 0 / fixed 26-slot counts, {} zero-inits all
        int left = 0;             // 視窗左邊界 / left boundary
        int ans = 0;              // 目前最大合法長度 / best valid length so far

        // 用範圍 for 需要索引，這裡改用傳統 for 以便同時存取 left/right
        // We need indices for both ends, so use a classic indexed for-loop
        for (int right = 0; right < (int)s.size(); ++right) {
            int c = s[right] - 'a';   // 字元轉 0..25 索引 / char to index 0..25
            ++cnt[c];                 // 加入視窗，計數加一 / add to window, increment count

            // 出現超過兩次就從左縮小視窗 / shrink from the left while it appears >2 times
            while (cnt[c] > 2) {
                --cnt[s[left] - 'a'];  // 移出最左字元 / drop the leftmost char's count
                ++left;                // 左邊界右移 / move left boundary right
            }

            // max() 取當前視窗長度與舊答案的較大值 / max() keeps the larger of window length and old answer
            ans = max(ans, right - left + 1);
        }
        return ans;   // 回傳結果 / return the result
    }
};
