[LeetCode] Maximum Length Substring With Two Occurrences

3090. Maximum Length Substring With Two Occurrences

Given a string s, return the maximum length of a substring such that it contains at most two occurrences of each character.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int maximumLengthSubstring(string s) {
int res = 0, l = 0, r = 0, n = s.length();
vector<int> freq(26);
while(r < n) {
while(r < n and freq[s[r]-'a'] < 2) {
freq[s[r]-'a']++;
r++;
}
res = max(res, r - l);
while(r < n and freq[s[r]-'a'] == 2) {
freq[s[l]-'a']--;
l++;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/03/24/PS/LeetCode/maximum-length-substring-with-two-occurrences/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.