//滑动窗口经典题目 , c++解法
class Solution {
public:
    int longestSubstring(string s, int k) {
        int n = s.size();
        unordered_map<char, int> h;    //用于记录已出现的字母
        int ans = 0, i = 0, j = 0, cnt = 0;
        while(j < n){
            if(h[s[j]] == 0){
                ++cnt;
            }
            ++h[s[j]];
            ++j;
            while(cnt > k){
                if(h[s[i]] == 1){
                    --cnt;
                }
                --h[s[i]];
                ++i;
            }
            ans = max(ans, j-i);
        }
        return ans;
    }
};