LeetCode 340. [Python] Longest Substring with At Most K Distinct Characters
原题链接
中等
作者:
徐辰潇
,
2021-02-09 08:44:57
,
所有人可见
,
阅读 686
class Solution:
def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int:
Dict = {}
count = 0
left = 0
right = 0
res = 0
while(right < len(s)):
if s[right] not in Dict:
Dict[s[right]] = 1
else:
Dict[s[right]] += 1
if Dict[s[right]] == 1:
count += 1
if count <= k:
res = max(res, right - left + 1)
else:
while(count > k and left <= right):
Dict[s[left]] -= 1
if Dict[s[left]] == 0:
count -= 1
left += 1
res = max(res, right - left + 1)
right += 1
return res