-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubstring.cpp
More file actions
36 lines (31 loc) · 882 Bytes
/
Substring.cpp
File metadata and controls
36 lines (31 loc) · 882 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <unordered_map>
using namespace std;
// Function to count substrings with at most K distinct characters
int atMostKDistinct(string s, int k) {
int n = s.size();
int left = 0, count = 0;
unordered_map<char, int> freq;
for (int right = 0; right < n; right++) {
freq[s[right]]++;
while ((int)freq.size() > k) {
freq[s[left]]--;
if (freq[s[left]] == 0) {
freq.erase(s[left]);
}
left++;
}
count += (right - left + 1);
}
return count;
}
// Function to count substrings with exactly K distinct characters
int exactlyKDistinct(string s, int k) {
return atMostKDistinct(s, k) - atMostKDistinct(s, k - 1);
}
int main() {
string s = "pqpqs";
int k = 2;
cout << exactlyKDistinct(s, k) << endl; // Output: 7
return 0;
}