[LeetCode] Longest Substring with At Least K Repeating Characters

395. Longest Substring with At Least K Repeating Characters

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.

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
class Solution {
public:
int longestSubstring(string s, int k) {
int res = 0;
int arr[26];
for(int uniq = 1; uniq <= 26; uniq++) {
memset(arr,0,sizeof(arr));
int l = 0, r = 0, cuniq = 0, overk = 0;
while(r < s.length()) {
if(cuniq <= uniq) {
if(!arr[s[r] - 'a']) cuniq++;
arr[s[r] - 'a']++;
if(arr[s[r] - 'a'] == k) overk++;
r++;
} else {
if(arr[s[l]-'a'] == 1) cuniq--;
if(arr[s[l]-'a'] == k) overk--;
arr[s[l]-'a']--;
l++;
}
if(cuniq == uniq and cuniq == overk) {
res = max(res, r - l);
}
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/08/PS/LeetCode/longest-substring-with-at-least-k-repeating-characters/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.