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:
- Number of ways in which the substring in range [L, R] can be formed using characters out of the range
- Minimum characters to be replaced to remove the given substring
- Number of Positions to partition the string such that atleast m characters with same frequency are present in each substring
- Number of ways to insert two pairs of parentheses into a string of N characters
- Remove minimum number of characters so that two strings become anagram
- Largest substring with same Characters
- Maximum length substring having all same characters after k changes
- Longest substring such that no three consecutive characters are same
- Minimum length substring with exactly K distinct characters
- Longest substring of only 4's from the first N characters of the infinite string
- Length of the longest substring without repeating characters
- Length of the longest substring with consecutive characters
- Searching characters and substring in a String in Java
- Print Longest substring without repeating characters
- Minimum steps to remove substring 010 from a binary string
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.