Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rtkwlf-hzzz/cea745a015845807c5953e151b85c41f to your computer and use it in GitHub Desktop.
Save rtkwlf-hzzz/cea745a015845807c5953e151b85c41f to your computer and use it in GitHub Desktop.
map.ch
# Online Python - IDE, Editor, Compiler, Interpreter
"""
Given a string s , find the length of the longest substring t that contains at most 2 distinct characters.
Example 1:
Input: "eceba"
Output: 3
Explanation: t is "ece" which its length is 3.
Example 2:
Input: "ccaabbb"
Output: 5
Explanation: t is "aabbb" which its length is 5.
"""
from collections import Counter
def lengthOfLongestSubstringTwoDistinct(s):
map = {}
res = 0
left = 0
for i,ch in enumerate(s):
map[ch] = map.get(ch,0)+1
while len(map)>2:
left_ch = s[left]
map[left_ch] = map.get(left_ch,0)-1
if map[left_ch]==0:
del map[left_ch]
left += 1
res = max(res, i-left+1)
return res
print(lengthOfLongestSubstringTwoDistinct("eceba"))
print(lengthOfLongestSubstringTwoDistinct("ccaabbb"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment