Longest Substring with At Most Two Distinct Characters
Description
null
Solution(javascript)
/**
 * @param {string} s
 * @return {number}
 */
const lengthOfLongestSubstringTwoDistinct = function (s) {
  const map = {}
  let count = 0
  let left = 0
  let max = 0
  for (let right = 0; right < s.length; right++) {
    const c = s[right]
    map[c] = (map[c] || 0) + 1
    if (map[c] === 1) {
      count += 1
    }
    while (count > 2) {
      map[s[left]] -= 1
      if (map[s[left]] === 0) {
        count -= 1
      }
      left += 1
    }
    max = Math.max(max, right - left + 1)
  }
  return max
}