Mid/Senior
Longest Substring with At Most K Distinct Characters
Given a string s and an integer k, return the length of the longest substring of s that contains at most k distinct characters.
A substring is a contiguous, non-empty sequence of characters within s. Your solution should efficiently track character frequencies while considering contiguous substrings.
Example 1
Input
s = "eceba", k = 2Output
3The substring "ece" has length 3 and contains at most 2 distinct characters.
Example 2
Input
s = "aa", k = 1Output
2The entire string "aa" has length 2 and contains only 1 distinct character.
Constraints
- 1 <= s.length <= 5 * 10^4
- 0 <= k <= 50
- s consists of English letters.