- Notifications
You must be signed in to change notification settings - Fork 625
/
Copy path159.py
32 lines (29 loc) · 953 Bytes
/
159.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
'''
Given a string, find the longest substring that contains only two unique characters. For example, given "abcbbbbcccbdddadacb", the longest substring that contains 2 unique character is "bcbbbbcccb".
'''
classSolution(object):
deflengthOfLongestSubstringTwoDistinct(self, s):
"""
:type s: str
:rtype: int
"""
ifnots:
return0
unique_char, start, result= {}, 0, 0
forindex, charinenumerate(s):
ifcharinunique_char:
unique_char[s] +=1
else:
unique_char[s] =1
iflen(unique_char) <=2:
result=max(result, index-start+1)
else:
whilelen(unique_char) >2:
char_index=s[start]
count=unique_char[char_index]
ifcount==1:
delunique_char[char_index]
else:
unique_char[char_index] -=1
start+=1
returnresult