#C13074. Longest Substring with Exactly K Distinct Characters
Longest Substring with Exactly K Distinct Characters
Longest Substring with Exactly K Distinct Characters
Given a string s
and an integer k
, your task is to find the length of the longest contiguous substring of s
that contains exactly k
distinct characters.
For example, consider the substring s[i...j]
, if there are exactly k
distinct characters, then the length of the substring is j-i+1
. You need to output the maximum such length. If no valid substring exists, output 0
.
Note that by "exactly k distinct characters" we mean that the substring should have no more and no less than k
unique characters. Formally, let the number of distinct characters in the substring be \(d\). The substring is valid if and only if \(d = k\).
inputFormat
The input consists of two lines:
- The first line contains the string
s
composed of lowercase English letters. - The second line contains an integer
k
, wherek \ge 0
.
outputFormat
Output a single integer denoting the length of the longest substring of s
that contains exactly k
distinct characters. If no such substring exists, output 0
.
eceba
2
3