贴一下我的做法 int main() { int n, k; string str; cin >> n >> k; cin >> str; ull res = 0; int cnt[128] = {0}; int kind = 0; for (char c : str) { cnt[c]++; if (cnt[c] == 1){ kind++; } } for (int i = 0, j = 0; i < n; i++) { char c = str[i]; cnt[c]--; if (cnt[c] == 0) { kind--; } while(j <= i && kind < k) { cnt[str[j]]++; if (cnt[str[j]] == 1) { kind++; } j++; } res += i - j + 1; } cout << res << endl; return 0; }