1 条题解

  • 0
    @ 2025-11-19 10:20:34
    • 同向双指针
    • 对每个 a[i]a[i],计算最小的 rr,使得 a[i]a[i]a[r]a[r] 满足要求
    • 随之 ii 变大,rr 必然不会变小
    #include <bits/stdc++.h>
    using namespace std;
    
    using i64 = long long;
    
    i64 solve(const string& s, int k) {
        int n = s.size(), maxi = 0;
        i64 ans = 0;
        vector<int> cnt(26, 0);  // 每个字符出现的次数
        for (int i = 0, r = -1; i < n; i++) {
            // maxi: cnt[i] 的最大值
            // 当 maxi >= k 时, r 才停止, 此时 maxi 必然等于 cnt[a[r]]
            while (maxi < k && r + 1 < n) {
                maxi = max(maxi, ++cnt[s[++r] - 'a']);
            }
            if (maxi >= k) {
                ans += n - r;
                cnt[s[i] - 'a']--;  // s[i] 出现的次数 -1
                if (s[i] == s[r]) maxi--;
            } else break;
        }
        return ans;
    }
    
    int main() {	
        ios::sync_with_stdio(false);
        cin.tie(0); cout.tie(0);
        
        int n, k;
        string s;
        cin >> n >> k >> s;
        cout << solve(s, k) << '\n';
    
        return 0;
    }
    
    • 1

    【普及】字符出现至少k次的子字符串

    信息

    ID
    185
    时间
    100ms
    内存
    32MiB
    难度
    4
    标签
    递交数
    46
    已通过
    24
    上传者