File tree 1 file changed +57
-0
lines changed
1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < bits/stdc++.h>
2
+ using namespace std ;
3
+
4
+ int mod=1e9 +7 ;
5
+ #define F (a,b,var ) for (int var=a;var<b;var++)
6
+ #define FAST_INP ios_base::sync_with_stdio (false );cin.tie(NULL )
7
+
8
+ int longestKUniqueCharSubstr (string &s, int k) {
9
+ if (s.size () == 0 ) return 0 ;
10
+ if (k == 0 or k > s.size ()) return -1 ;
11
+
12
+ const int CHAR_RANGE = 128 ;
13
+ int frequency[CHAR_RANGE] = {0 };
14
+ unordered_set<char > window; // sliding window -- at any instance, there has to be k characters in the window
15
+ int n = s.length ();
16
+ int low, high; // low ... high -- keep track of window boundaries
17
+ int begin = 0 , end = 0 ;
18
+
19
+ for (low = 0 , high = 0 ; high < n; high++) {
20
+ window.insert (s[high]);
21
+ frequency[s[high]]++;
22
+
23
+
24
+ while (window.size () > k) { // if the window exceeds k characters --
25
+ --frequency[s[low]]; // remove char from left
26
+ if (frequency[s[low]] == 0 ) { // if the character frequency becomes 0, it means the character is no more present in the window; so erase it
27
+ window.erase (s[low]);
28
+ }
29
+ low++; // increment left boundary
30
+ }
31
+
32
+ if (high - low > end - begin) { // store the ax
33
+ end = high, begin = low;
34
+ }
35
+ }
36
+ return end - begin + 1 ;
37
+ }
38
+
39
+
40
+ int main ()
41
+ {
42
+ // code
43
+
44
+ FAST_INP;
45
+ int T;
46
+ cin>>T;
47
+ while (T--)
48
+ {
49
+ int k;
50
+ string s;
51
+
52
+ cin>>s>>k;
53
+ cout<<longestKUniqueCharSubstr (s, k)<<" \n " ;
54
+
55
+ }
56
+ return 0 ;
57
+ }
You can’t perform that action at this time.
0 commit comments