#K14041. Longest Substring with At Most K Distinct Characters
Longest Substring with At Most K Distinct Characters
Longest Substring with At Most K Distinct Characters
You are given a string s
and an integer m. Your task is to determine the length of the longest contiguous substring of s
that contains at most m
distinct characters. More formally, if you let F(s, m) denote the desired length, then you must compute:
\( F(s, m) = \max_{[i, j]} \{ j - i + 1 \}\)
subject to the constraint that the substring s[i...j]
has at most m distinct characters. It is recommended to use a sliding window algorithm to efficiently solve this problem.
inputFormat
The input is read from standard input (stdin) and has the following format:
- The first line contains an integer
t
denoting the number of test cases. - For each test case, there are two lines:
- The first line contains an integer
m
(\( m \ge 0 \)). - The second line contains the string
s
. The string will not contain spaces.
- The first line contains an integer
Note: If the string is empty or if m
is 0, the answer is 0.
outputFormat
For each test case, output a single line containing the length of the longest substring with at most m distinct characters.
The output should be printed to standard output (stdout).
## sample3
2
abcba
1
aaa
3
aabacbebebe
3
3
7
</p>