forked from krish-ag/HacktoberFest22-Repo-DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
longestuniquecharsubstring.cpp
48 lines (40 loc) · 1.19 KB
/
longestuniquecharsubstring.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
#include<bits/stdc++.h>
using namespace std;
int longestKSubstr(string s, int K) {
int i=0;
int j=0;
map<char,int> v;
int g=-1;
while(j<s.length())
{
v[s[j]]++;
//cout<<"g = "<<g<<endl;
if(v.size()<K)
{
j++;
}
else if(v.size()==K)
{
g = max(g,j-i+1);
j++;
}
else if(v.size()>K)
{
while(v.size()>K)
{
v[s[i]]--;
if(v[s[i]]==0)
{
v.erase(s[i]);
}
i++;
}
j++;
}
}
return g;
}
int main(){
string str = "aabacbebebe";
cout<<"Longest length of substring with 3 unique characters is "<<longestKSubstr(str,3);
}