-
Notifications
You must be signed in to change notification settings - Fork 1
/
Longest K unique characters substring.cpp
57 lines (52 loc) · 1.19 KB
/
Longest K unique characters substring.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
#include<bits/stdc++.h>
using namespace std;
int longestSubstr(string, int);
int main(){
int t, k;
string s;
cin >> t;
while(t--){
cin >> s >> k;
cout << longestSubstr(s, k) << endl;
}
return 0;
}
int longestSubstr(string s, int k){
queue<char> q;
unordered_map<char, int> um;
int max = 0;
bool res = false;
for(int i = 0; i < s.length(); i++){
if(um.size() < k){
q.push(s[i]);
um[s[i]]++;
if(um.size() == k)
res = true;
}
else if(um.size() == k){
res = true;
if(um.find(s[i]) != um.end()){
q.push(s[i]);
um[s[i]]++;
}
else{
while(1){
char temp = q.front();
q.pop();
um[temp]--;
if(um[temp] == 0){
um.erase(temp);
break;
}
}
q.push(s[i]);
um[s[i]]++;
}
}
if(max < q.size())
max = q.size();
}
if(!res)
return -1;
return max;
}