-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path25_Question.cpp
More file actions
66 lines (48 loc) · 1.22 KB
/
25_Question.cpp
File metadata and controls
66 lines (48 loc) · 1.22 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// You are given a string s consisting only lowercase alphabets and an integer k. Your task is to find the length of the longest substring
// that contains exactly k distinct characters.
// Note : If no such substring exists, return -1.
// Examples:
// Input: s = "aabacbebebe", k = 3
// Output: 7
// Explanation: The longest substring with exactly 3 distinct characters is "cbebebe", which includes 'c', 'b', and 'e'.
// Input: s = "aaaa", k = 2
// Output: -1
// Explanation: There's no substring with 2 distinct characters.
#include <bits/stdc++.h>
using namespace std;
int longestSubstr(string &s, int k)
{
int n = s.length();
int max_len = -1;
int l = 0, r = 0;
vector<int> freq(26, 0);
int cnt = 0;
while (r < n)
{
freq[s[r] - 'a']++;
if (freq[s[r] - 'a'] == 1)
cnt++;
while (cnt > k)
{
freq[s[l] - 'a']--;
if (freq[s[l] - 'a'] == 0)
cnt--;
l++;
}
if (cnt == k)
{
max_len = max(max_len, r - l + 1);
}
r++;
}
return max_len;
}
int main()
{
string s;
cin >> s;
int k;
cin >> k;
cout << longestSubstr(s, k);
return 0;
}