Leetcode 1423 Solution
This article provides solution to leetcode question 1423 (maximum-number-of-occurrences-of-a-substring)
Access this page by simply typing in "lcs 1423" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/maximum-number-of-occurrences-of-a-substring
Solution
class Solution:
def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int:
l = 0
r = 0
str_cnt = collections.defaultdict(int)
ch_cnt = collections.defaultdict(int)
while r < len(s):
ch_cnt[s[r]] += 1
if r - l + 1 > minSize:
if s[l] in ch_cnt and ch_cnt[s[l]] == 1:
del ch_cnt[s[l]]
else:
ch_cnt[s[l]] -= 1
l += 1
if r - l + 1 == minSize and len(ch_cnt) <= maxLetters:
str_cnt[s[l:r + 1]] += 1
r += 1
best_str_cnt = 0
best_str = ""
for s, cnt in str_cnt.items():
if cnt > best_str_cnt:
best_str_cnt = cnt
best_str = s
return best_str_cnt