![]() |
VOOZH | about |
Given a string s and a non negative integer k, find the length of the longest substring that contains exactly k distinct characters. If no such substring exists, return -1.
Examples:
Input: s = "aabacbebebe", k = 3
Output: 7
Explanation: The longest substring with exactly 3 distinct characters is "cbebebe", which includes 'c', 'b', and 'e'.Input: s = "aaaa", k = 2
Output: -1
Explanation: The string contains only one unique character, so there's no substring with 2 distinct characters.Input: s = "aabaaab", k = 2
Output: 7
Explanation: The entire string "aabaaab" has exactly 2 unique characters 'a' and 'b', making it the longest valid substring.
Table of Content
This brute-force approach checks all substrings starting from each index. It uses a set to track unique characters, and whenever a substring has exactly
kdistinct characters, it updates the maximum length.
7
7
7