-
Notifications
You must be signed in to change notification settings - Fork 17
/
longest-substring-with-at-least-k-repeating-characters.py
75 lines (50 loc) · 1.79 KB
/
longest-substring-with-at-least-k-repeating-characters.py
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
from typing import Counter
class CharLessThanK:
def __init__(self, k: int) -> None:
self.k = k
self.counter: Counter[str] = Counter()
self.count = 0
def add(self, char: str) -> None:
if self.counter[char] == 0:
self.count += 1
self.counter[char] += 1
if self.counter[char] == self.k:
self.count -= 1
def remove(self, char: str) -> None:
if self.counter[char] == self.k:
self.count += 1
self.counter[char] -= 1
if self.counter[char] == 0:
self.count -= 1
self.counter.pop(char)
class Solution:
def longestSubstring(self, s: str, k: int) -> int:
longest_substring = 0
for chars in range(1, len(set(s)) + 1):
start, end = 0, 0
counter = CharLessThanK(k)
while end < len(s):
counter.add(s[end])
while len(counter.counter.keys()) > chars:
counter.remove(s[start])
start += 1
end += 1
if counter.count == 0:
longest_substring = max(longest_substring, end - start)
return longest_substring
def longestSubstringBruteForce(self, s: str, k: int) -> int:
longest_substring = 0
start, end = 0, 0
counter = CharLessThanK(k)
while start < len(s):
while end < len(s):
counter.add(s[end])
end += 1
if counter.count == 0:
longest_substring = max(longest_substring, end - start)
while counter.count > 0:
counter.remove(s[end - 1])
end -= 1
counter.remove(s[start])
start += 1
return longest_substring