![]() |
VOOZH | about |
Given a string s consisting of only lowercase English letters and an integer k, count the total number of substrings (not necessarily distinct) of s that contain exactly k distinct characters.
Note:
Examples:
Input: s = "abc", k = 2
Output: 2
Explanation: Possible substrings are ["ab", "bc"]Input: s = "aba", k = 2
Output: 3
Explanation: Possible substrings are ["ab", "ba", "aba"]Input: s = "aa", k = 1
Output: 3
Explanation: Possible substrings are ["a", "a", "aa"]
Table of Content
The idea is to check every possible substring by iterating through all possible starting positions (i) and ending positions (j) in the string. For each substring, maintain a boolean array to track distinct characters and a counter for the number of distinct characters. As it expands the substring from left to right, it updates the distinct character count by checking if each new character has been seen before. Whenever the number of distinct characters exactly matches the given k, it increments the answer count.
2
The idea is to use sliding window technique to efficiently count substrings with at most k distinct characters, and then subtract the count of substrings with at most k-1 distinct characters to obtain the number of substrings with exactly k distinct characters.
Step by step Implementation:
2