340. Longest Substring with At Most K Distinct Characters
这题是典型的前向型指针的模板题
class Solution(object):
def lengthOfLongestSubstringKDistinct(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
if k == 0:
return 0
hash = {}
j = 0
counter = 0
res = 0
for i in range(len(s)):
while j < len(s) and (s[j] in hash or counter < k):
if s[j] in hash:
hash[s[j]] += 1
else:
hash[s[j]] = 1
counter += 1
res = max(res, j-i+1)
j += 1
hash[s[i]] -= 1
if hash[s[i]] == 0:
hash.pop(s[i], 0)
counter -= 1
return res