159. Longest Substring with At Most Two Distinct Characters
这题比较简单,前向型指针的模板套用一下就可以了
class Solution(object):
def lengthOfLongestSubstringTwoDistinct(self, s):
"""
:type s: str
:rtype: int
"""
# 前向型指针
j = 0
max_length = 0
h = {}
for i in range(len(s)):
while j < len(s) and self.valid(h, s, j):
h[s[j]] = h.get(s[j], 0) + 1
max_length = max(max_length, j - i + 1)
j += 1
h[s[i]] -= 1
if h[s[i]] == 0:
h.pop(s[i])
return max_length
def valid(self, h, s, j):
if len(h) <= 1:
return True
return s[j] in h