Skip to content

Commit f712d46

Browse files
authored
Merge pull request #827 from sriharsha200/mytech
Longest Substring with At Least K Repeating Characters
2 parents 75b5dbb + bf84842 commit f712d46

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/*
2+
Given a string s and an integer k, return the length of the longest substring of s such that the frequency of each character in this substring is greater than or equal to k.
3+
Example 1:
4+
Input: s = "aaabb", k = 3
5+
Output: 3
6+
Explanation: The longest substring is "aaa", as 'a' is repeated 3 times.
7+
Example 2:
8+
Input: s = "ababbc", k = 2
9+
Output: 5
10+
Explanation: The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times.
11+
*/
12+
#include<bits/stdc++.h>
13+
using namespace std;
14+
int longestSubstring(string s, int k) {
15+
unordered_map<int,int>m; // Keep Track of frequency of each character
16+
for(int i=0;i<s.length();i++)
17+
m[s[i]]+=1;
18+
int i=0,left=s.length(),rit=0;
19+
while( i < s.length() && k <= m[s[i]]){ // Sliding it till we need our first string
20+
i++;
21+
}
22+
if(i==(s.length()))
23+
return s.length();
24+
if(s.length()==0)
25+
return 0;
26+
if(i<s.length())
27+
left=longestSubstring(s.substr(0,i),k);
28+
while(i<s.length() && m[s[i]]<k) // to check if more continious characters are having count less than k
29+
i++;
30+
if((s.length()-i-1)>0)
31+
rit=longestSubstring(s.substr(i,s.length()),k);
32+
int ans=max(left,rit);
33+
return ans;
34+
}
35+
int main(){
36+
string s;
37+
cin>>s;
38+
int k;
39+
cin>>k;
40+
cout<<longestSubstring(s,k);
41+
return 0;
42+
}

0 commit comments

Comments
 (0)