159 Longest Substring with At Most Two Distinct Characters

Given a string s, return the length of the longest substring (A substring is a contiguous non-empty sequence of characters within a string.) 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.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
    def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int:
        left = right = -1
        d = defaultdict(int)
        res = 0
        while right < len(s)-1:
            right += 1
            d[s[right]] += 1
            while len(d) > 2:
                left += 1
                d[s[left]] -= 1
                if d[s[left]] == 0:
                    del d[s[left]]
            res = max(res, right-left)
        return res