Given a string str and an integer k. The task is to count the occurrences of sub-strings of length k that consist of the same characters. There can be multiple such sub-strings possible of length k, choose the count of the one which appears the maximum number of times as the sub-string (non-overlapping) of str.
Input: str = “aaacaabbaa”, k = 2 Output: 3 “aa” and “bb” are the only sub-strings of length 2 that consist of the same characters. “bb” appears only once as a sub-string of str whereas “aa” appears thrice (which is the answer)
Approach: Iterate over all the characters from ‘a’ to ‘z’ and count the number of times a string of length k consisting only of the current character appears as a sub-string of str. Print the maximum of these counts in the end.
Steps to solve the problem:
Initialize maxSubStr to 0 and n to the size of the string s.
Iterate over all characters of the English alphabet using a loop from 0 to 25.
For each character, store it in a variable ch.
Initialize a variable curr to 0.
Use another loop to iterate over all possible substrings of length k in the string s.
If the current character of the string s is not the same as the character ch, continue with the next iteration of the loop.
If the current character is the same as ch, count the number of consecutive characters in the substring that are the same as ch, using a variable cnt.
If cnt is not equal to k, continue with the next iteration of the loop.
If cnt is equal to k, increment the variable curr.
After the inner loop, update maxSubStr to the maximum of its current value and curr.
After the outer loop, return maxSubStr as the result.
Below is the implementation of the above approach:
Please Login to comment...