Problem · Sliding Window
Longest Substring With At Most Two Distinct Characters
Learn this problemProblem statement
Given a string s, return the length of its longest contiguous substring containing at most two distinct characters.
A substring must occupy consecutive positions. Repeated occurrences of one character count as one distinct character. An empty string has answer 0.
Function
longestTwoDistinct(s: String) → intExamples
Example 1
s = "eceba"return = 3The substring ece has length 3 and uses only e and c. Every longer substring contains at least three distinct characters.
Example 2
s = "ccaabbb"return = 5The substring aabbb has length 5. Adding either preceding c would introduce a third distinct character.
Constraints
0 <= s.length <= 50000scontains only lowercase English letters.