Given a string s, return the length of the longest substring that contains at most two distinct characters.
Example 1:
Input: s = "eceba"
Output: 3
Explanation: The substring is "ece" which its length is 3.
Example 2:
Input: s = "ccaabbb"
Output: 5
Explanation: The substring is "aabbb" which its length is 5.
Constraints:
1 <= s.length <= 105
s consists of English letters.
Solutions
Solution 1
Thinking
Longest substring with at most two distinct characters. \(n\le 10^5\), so enumerating endpoints is \(O(n^2)\). The distinct count grows with the right end and shrinks with the left. Extend right while counting; when there are more than two kinds, move left. Update the answer on a valid window.