LeetCode 159. [Python] Longest Substring with At Most Two Distinct Characters
原题链接
中等
作者:
徐辰潇
,
2020-07-11 22:45:10
,
所有人可见
,
阅读 727
class Solution:
def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int:
#TC: O(len(s))
#SC: O(1)
if len(s) == 0:
return 0
left = 0
right = 1
Dict = collections.defaultdict(int)
Dict[s[0]] = 1
res = 1
while(right < len(s)):
Dict[s[right]] += 1
if len(Dict) <= 2:
Len = right - left + 1
res = max(Len, res)
else:
while(left < right):
left += 1
Dict[s[left-1]] -= 1
if Dict[s[left-1]] == 0:
del Dict[s[left-1]]
if len(Dict) <= 2:
Len = right - left + 1
res = max(Len, res)
break
right += 1
return res