-
Notifications
You must be signed in to change notification settings - Fork 55
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
794757d
commit 7b56125
Showing
1 changed file
with
50 additions
and
0 deletions.
There are no files selected for viewing
50 changes: 50 additions & 0 deletions
50
Longest K unique characters substring - GFG/longest-k-unique-characters-substring.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
//{ 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) { | ||
// your code here | ||
unordered_map<char,int>mp; | ||
int n=s.size(); | ||
int start=0,end=0,ans=-1; | ||
for(end=0;end<n;end++){ | ||
mp[s[end]]++; | ||
if(mp.size()>k){ | ||
while(start<=end and start<n and mp.size()>k){ | ||
mp[s[start]]--; | ||
if(mp[s[start]]==0){ | ||
mp.erase(s[start]); | ||
} | ||
start++; | ||
} | ||
} | ||
if(mp.size()==k){ | ||
ans=max(ans,end-start+1); | ||
} | ||
} | ||
return ans; | ||
} | ||
}; | ||
|
||
//{ 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 |