跳转至

至少有 K 个重复字符的最长子串⚓︎

Leetcode题目链接

描述⚓︎

详见中文题目链接

解答⚓︎

class Solution {
public:
    int longestSubstring(string s, int k) {
        int res = 0;
        int n = s.size();

        for (int require = 1; require <= 26; require++) {
            vector<int> cnts(256, 0);
            int collectedKinds = 0, satisfiedKinds = 0;
            for (int left = 0, right = 0; right < n; right++) {
                cnts[s[right]]++;

                if (cnts[s[right]] == 1) collectedKinds++;
                if (cnts[s[right]] == k) satisfiedKinds++;

                while (collectedKinds > require) {
                    if (cnts[s[left]] == 1) collectedKinds--;
                    if (cnts[s[left]] == k) satisfiedKinds--;
                    cnts[s[left]]--;
                    left++;
                }

                if (satisfiedKinds == require) {
                    res = max(res, right - left + 1);
                }
            }
        }

        return res;
    }
};