Given a string ‘str’ and an integer ‘k’, the task is to count the number of sub-strings of length ‘k’ which are comprised of the same character. Given string contains only lowercase alphabets.
Input: str = "aaaabbbccdddd", k=4 Output: 2 The sub-strings of length 4 which contain identical characters are 'aaaa' and 'dddd'. So, the count is 2. Input: str = "aaaaaa", k=4 Output: 3
A simple approach:
- Find all the sub-strings of the string that are of length ‘k’.
- Check if those sub-strings are composed of only ‘1’ character.
- If the above conditions hold then increase the count.
- Display the count.
Efficient approach: We will use Window sliding technique to solve this problem.
- Take a sub-string of length ‘k’ (which is the first ‘k’ characters).
- Then, add next character to the sub-string.
- If the length of the sub-string is greater than ‘k’ then remove the character from the beginning of the string.
- And, count the frequency of the characters in the sub-string with the help of a map.
- If the frequency of one of the sub-string’s character is equal to length of the sub-string itself i.e. all the characters are same.
- Then, increase the count else repeat the steps above until the there’s no more character to add in the end.
- Display the total count in the end.
Below is the implementation of the above approach :
- Count substrings that starts with character X and ends with character Y
- Count of substrings which contains a given character K times
- Number of substrings with count of each character as k
- Count substrings with each character occurring at most k times
- Print Kth character in sorted concatenated substrings of a string
- Count all Prime Length Palindromic Substrings
- Convert all substrings of length 'k' from base 'b' to decimal
- Count number of distinct substrings of a given length
- Find number of substrings of length k whose sum of ASCII value of characters is divisible by k
- Minimum K such that every substring of length atleast K contains a character c
- Check if the frequency of any character is more than half the length of the string
- Minimize the length of string by removing occurrence of only one character
- Length of the largest substring which have character with frequency greater than or equal to half of the substring
- Find a string such that every character is lexicographically greater than its immediate next character
- Longest Common Prefix using Character by Character Matching
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.