Skip to content

Commit f56ce18

Browse files
authored
Create longest-substring-with-at-least-k-repeating-characters.cpp
1 parent 9c6bb0a commit f56ce18

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// Time: O(26 * n) = O(n)
2+
// Space: O(26) = O(1)
3+
4+
// Recursive solution.
5+
class Solution {
6+
public:
7+
int longestSubstring(string s, int k) {
8+
return longestSubstringHelper(s, k, 0, s.size());
9+
}
10+
11+
private:
12+
int longestSubstringHelper(const string& s, int k, int start, int end) {
13+
vector<int> count(26);
14+
for (int i = start; i < end; ++i) {
15+
++count[s[i] - 'a'];
16+
}
17+
18+
int max_len = 0;
19+
for (int i = start; i < end;) {
20+
while (i < end && count[s[i] - 'a'] < k) {
21+
++i;
22+
}
23+
if (i == end) {
24+
break;
25+
}
26+
27+
int j = i;
28+
while (j < end && count[s[j] - 'a'] >= k) {
29+
++j;
30+
}
31+
if (i == start && j == end) {
32+
return end - start;
33+
}
34+
35+
max_len = max(max_len, longestSubstringHelper(s, k, i, j));
36+
i = j;
37+
}
38+
return max_len;
39+
}
40+
};

0 commit comments

Comments
 (0)