-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathGFG_LongestKUniqueCharSubstring.cpp
60 lines (50 loc) · 1.23 KB
/
GFG_LongestKUniqueCharSubstring.cpp
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
/*
Longest K unique characters substring
https://practice.geeksforgeeks.org/problems/longest-k-unique-characters-substring0853/1/
*/
// { Driver Code Starts
//Initial template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function template for C++
class Solution{
public:
int longestKSubstr(string s, int k) {
unordered_map<char, int> umap;
int n = s.length();
int i = 0, j = 0;
int longest=-1;
while(j<n)
{
umap[s[j]]++;
if(umap.size() == k) // num of unique char is == k;
longest = max(longest, j-i+1);
else if(umap.size() > k)
{
while(umap.size()>k)
{
umap[s[i]]--;
if(umap[s[i]] == 0)umap.erase(s[i]);
i++;
}
}
j++;
}
return longest;
}
};
// { Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
string s;
cin >> s;
int k;
cin >> k;
Solution ob;
cout << ob.longestKSubstr(s, k) << endl;
}
}
// } Driver Code Ends