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 <= 100
s
consists only of lowercase English letters.
Solution
Python3
class Solution:
def maximumLengthSubstring(self, s: str) -> int:
N = len(s)
res = 0
i = 0
counter = Counter()
for j, x in enumerate(s):
counter[x] += 1
while counter[x] > 2:
counter[s[i]] -= 1
i += 1
res = max(res, j - i + 1)
return res