Longest Stretch With At Most K Different Letters
Problem statement
You are given a string s and an integer k. Find the longest stretch of consecutive characters in s that uses at most k different letters, and return its length.
- A letter that repeats inside the stretch counts as one different letter.
- If no letter is allowed (
k = 0), only the empty stretch qualifies, so the answer is0.
Function
longestKDistinct(s: String, k: int) → intExamples
Example 1
s = "abaccc"k = 2return = 4The substring "accc" (indexes 2 to 5) has only 'a' and 'c', and its length is 4. Any longer substring would also contain the 'b' at index 1 together with 'a' and 'c', which is 3 different letters.
Example 2
s = "zzyyxx"k = 5return = 6The whole string uses only 3 different letters, which is fewer than k = 5, so the answer is its full length, 6.
Example 3
s = "xyz"k = 0return = 0With k = 0 no letter may appear, so only the empty substring qualifies. The answer is 0.
Constraints
1 <= s.length <= 5 * 10^4scontains only lowercase English letters.0 <= k <= 26