Given a string str consisting only of lowercase English alphabets, the task is to count the number of ways to remove exactly one sub-string from str such that all remaining characters are same.
Note: There are at least two different characters in str and we can remove the whole string as well.
Input: str = “abaa”
We can remove the following sub-strings to satisfy the given condition:
str[0:1], str[0:2], str[0:3], str[1:1], str[1:2] and str[1:3]
Input: str = “geeksforgeeks”
We remove complete string.
We remove all except first.
We remove all except last
- Store the length of prefix and suffix of same characters from the string in variables count_left and count_right.
- It is obvious that this prefix and suffix wouldn’t overlap, since there are at least two different characters in str.
- Now there are 2 cases:
- When str = str[n – 1] then every character of the prefix (including the character just after the prefix ends) will act as the starting character of the sub-string and every character of the suffix (including the character just before the suffix starts) will act as the ending character of the sub-string. So, total valid sub-strings will be count = (count_left + 1) * (count_right + 1).
- When str != str[n – 1]. then count = count_left + count_right + 1.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.