Count K-Beautiful Substrings
At Snap, we often process user-generated content, including text. Analyzing properties of text, such as character diversity within specific segments, can be crucial for content moderation, recommendation engines, or even stylistic analysis for creative tools. This problem challenges you to identify and count specific types of substrings based on their character diversity.
You are tasked with implementing a function countKBeautifulSubstrings that takes a string s and an integer k. Your function should return the total number of substrings of s that contain exactly k distinct characters.
s: A string consisting of lowercase English letters.k: An integer representing the required number of distinct characters.s will result in 0 beautiful substrings.k is greater than the total distinct characters available in s, the count will be 0.Examples
Example 1
Input:
s = "aba", k = 2
Output:
3
Note:
The K-beautiful substrings are "ab", "ba", and "aba".
Example 2
Input:
s = "aabc", k = 2
Output:
3
Note:
The K-beautiful substrings are "ab", "aab", and "bc".
Example 3
Input:
s = "aaaaa", k = 1
Output:
15
Note:
All substrings of "aaaaa" contain exactly 1 distinct character ('a'). The number of substrings is n*(n+1)/2 = 5*6/2 = 15.
Example 4
Input:
s = "abcde", k = 4
Output:
2
Note:
The K-beautiful substrings are "abcd" and "bcde".
Constraints
1 <= s.length <= 10^51 <= k <= 26 (since s consists only of lowercase English letters)s consists only of lowercase English letters ('a'-'z').Loading editor...