159. Longest Substring with At Most Two Distinct Characters
Given a string, find the length of the longest substring T that contains at most 2 distinct characters.
For example, Given s = "eceba",
T is "ece" which its length is 3.
Solution: HashMap
import collections
class Solution(object):
def lengthOfLongestSubstringKDistinct(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
max_len = 0
count = collections.defaultdict(int)
slow = 0
for fast, char in enumerate(s):
count[char] += 1
while len(count) > k:
left = s[slow]
count[left] -= 1
if count[left] == 0:
del count[left]
slow += 1
max_len = max(max_len, fast - slow + 1)
return max_len