Longest Substring with At Most K Distinct Characters
Given a string s and an integer k, find the length of the longest substring t of s such that t contains at most k distinct characters. Your solution should return this length.
[ "eceba", "2" ]
Explanation. The longest substring with at most 2 distinct characters is "ece", "ceb" or "eba". All have length 3.
[ "aaacccbbbaaa", "1" ]
Explanation. With k=1, the longest substrings are "aaa", "ccc", "bbb", each of length 3.
[ "abaccc", "2" ]
Explanation. The longest substring with at most 2 distinct characters is "accc", which has 'a' and 'c' as distinct characters, and a length of 4.
[ "abcde", "3" ]
Explanation. The longest substrings are "abc", "bcd", "cde", each having 3 distinct characters and a length of 3.
[ "aaaaaaa", "5" ]
Explanation. The entire string "aaaaaaa" has only 1 distinct character ('a'). Since k=5, the entire string satisfies the condition, and its length is 7.
[ "a", "1" ]
Explanation. The string "a" has 1 distinct character. k=1, so the length is 1.
[ "ab", "1" ]
Explanation. The longest substring with at most 1 distinct character is "a" or "b", each of length 1.
Follow-up: Can you adapt your solution if the input string `s` could contain Unicode characters (beyond basic ASCII), and `k` could be very large (up to `s.length`)?
- `1 <= s.length <= 5 * 10^4` - `s` consists of English lowercase letters. - `1 <= k <= 26`
- Views
- 3