Problem 220
Substrings with K Distinct Characters
Medium · 20 pts · String, Sliding Window, Hash Table
Problem
You are given a string S and a number K. Count the substrings (contiguous blocks) of S that contain exactly K different characters. Substrings at different positions are counted separately, even if they are equal. Counting "exactly K" directly is awkward, but counting "at most K" is easy with a sliding window: for each right end, the number of valid substrings ending there is the window length. Then exactly(K) = atMost(K) - atMost(K - 1).
Input
First line: string S (lowercase letters). Second line: integer K.
Output
Print the number of substrings.
Constraints
1 <= |S| <= 100000; 1 <= K <= 26
Example input
pqpqs 2
Example output
7
Explanation
In "pqpqs" with K = 2, the substrings with exactly 2 distinct characters are pq, qp, pq, qs, pqp, qpq and pqpq. That is 7 substrings.