[LeetCode] Maximum Number of Occurrences of a Substring

1297. Maximum Number of Occurrences of a Substring

Given a string s, return the maximum number of ocurrences of any substring under the following rules:

  • The number of unique characters in the substring must be less than or equal to maxLetters.
  • The substring size must be between minSize and maxSize inclusive.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
int maxFreq(string s, int maxLetters, int minSize, int maxSize) {
unordered_map<string, int> freq;
int res = 0, n = s.length(), l = 0, r = 0, count = 0, counter[26] = {};
while(r < n) {
int R = s[r++] - 'a';
if(++counter[R] == 1) count++;
while(count > maxLetters or r - l > minSize) {
int L = s[l++] - 'a';
if(--counter[L] == 0) count--;
}
if(r - l == minSize)
res = max(res, ++freq[s.substr(l, r - l)]);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/02/PS/LeetCode/maximum-number-of-occurrences-of-a-substring/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.