LeetCode Top Interview Questions 340. Longest Substring with At Most K Distinct Characters (Java版; Hard)
题目描述
Given a string, find the length of the longest substring T that contains at most k distinct characters.
Example 1:
Input: s = "eceba", k = 2
Output: 3
Explanation: T is "ece" which its length is 3.
Example 2:
Input: s = "aa", k = 1
Output: 2
Explanation: T is "aa" which its length is 2.
classSolution:
def lengthOfLongestSubstringKDistinct(self, s: str, k:int)->int:
res =0
left =0
queue ={}for right in range(len(s)):
queue.setdefault(s[right],0)
queue[s[right]]+=1whilelen(queue)> k:
queue[s[left]]-=1if queue[s[left]]==0:
queue.pop(s[left])
left +=1
res =max(res, right - left +1)return res