Problem · String
Longest Substring with At Most K Distinct Characters
Learn this problemProblem statement
Given a string s and an integer k, return the maximum length of a contiguous substring containing at most k distinct characters.
Return 0 when k is zero or s is empty.
Function
longestSubstringAtMostKDistinct(s: String, k: int) → intExamples
Example 1
s = "eceba"k = 2return = 3The substring ece has two distinct characters.
Example 2
s = "aa"k = 1return = 2The entire string uses one distinct character.
Constraints
0 <= s.length <= 2000000 <= k <= 200000scontains printable ASCII characters.