LC 0159 [M] Longest Substring with At Most Two Distinct Characters - ALawliet/algorithms GitHub Wiki

class Solution:
    def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int:
          char_to_count = Counter()
          max_len = 0
          l = 0
          for r in range(len(s)):
              char_to_count[s[r]] += 1
              while len(char_to_count) > 2:
                char_to_count[s[l]] -= 1
                if char_to_count[s[l]] == 0: del char_to_count[s[l]]
                l += 1 
              max_len = max(max_len, r - l + 1)
          return max_len