Python3,双指针,注意K为0的情况。
class Solution:
def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int:
if k == 0:
return 0
charMap = {}
result = 0
i = j = 0
while j < len(s):
if s[j] in charMap:
charMap[s[j]] += 1
j += 1
elif len(charMap) < k:
charMap[s[j]] = 1
j += 1
else:
if j - i > result:
result = j - i
charMap[s[i]] -= 1
if charMap[s[i]] == 0:
del charMap[s[i]]
i += 1
if j - i > result:
result = j - i
return result
[leetcode]Longest Substring with At Most K Distinct Characters
原文:https://www.cnblogs.com/lautsie/p/12245564.html