3090. Maximum Length Substring With Two Occurrences
Description
Given a string s, return the maximum length of a substring such that it contains at most two occurrences of each character.
Example 1:
Input: s = "bcbbbcba"
Output: 4
Explanation:
The following substring has a length of 4 and contains at most two occurrences of each character:"bcbbbcba".Example 2:
Input: s = "aaaa"
Output: 2
Explanation:
The following substring has a length of 2 and contains at most two occurrences of each character:"aaaa".
Constraints:
2 <= s.length <= 100sconsists only of lowercase English letters.
Solutions
Solution 1: Two Pointers
Thinking
Every character in the substring may appear at most twice. \(n \le 100\) would allow enumeration, but the constraint is a classic sliding window.
After the right end absorbs a character, if some count exceeds \(2\) the left end must advance until that count is back to \(2\). A valid window updates the maximum length.
A hash of counts plus two pointers does this in one pass.
We use two pointers \(l\) and \(r\) to maintain a sliding window, and an array \(cnt\) to record the occurrence times of each character in the window.
In each iteration, we add the character \(c\) at the pointer \(r\) into the window, then check if \(cnt[c]\) is greater than \(2\). If it is, we move the pointer \(l\) to the right until \(cnt[c]\) is less than or equal to \(2\). At this point, we update the answer \(ans = \max(ans, r - l + 1)\).
Finally, we return the answer \(ans\).
The time complexity is \(O(n)\), where \(n\) is the length of the string \(s\). The space complexity is \(O(|\Sigma|)\), where \(\Sigma\) is the character set, and in this problem, \(\Sigma = 26\).
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |