Given a string S and a character C, the task is to count the number of substrings of S that contains only the character C.
Input: S = “0110111”, C = ‘1’
The substrings containing only ‘1’ are:
“1” — 5 times
“11” — 3 times
“111” — 1 time
Hence, the count is 9.
Input: S = “geeksforgeeks”, C = ‘e’
The simplest approach is to generate all possible substrings of the given string S and count the substrings which contains only character C.
Time Complexity: O(N3)
Space Complexity: O(1)
To optimize the above approach, the fact that a string of length N forms N*(N+1)/2 substrings can be applied. Therefore, for N consecutive occurrence of character C in the string, N*(N+1)/2 substrings are generated. Hence, iterate through the entire length of the string S and for each consecutive substring of character C, count the possible number of substrings possible from them and add to the total count of substrings possible.
S = “0110111”, C = ‘1’
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)
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.
- Count of substrings of a Binary string containing only 1s
- Minimize length of Substrings containing at least one common Character
- Count substrings that starts with character X and ends with character Y
- Count of Subsets containing only the given value K
- Count of substrings of a binary string containing K ones
- Count of substrings formed using a given set of characters only
- Count of substrings which contains a given character K times
- Count of substrings consisting only of vowels
- Number of substrings with count of each character as k
- Count substrings with each character occurring at most k times
- Count all substrings having character K
- Lexicographically smallest substring with maximum occurrences containing a's and b's only
- Longest Subsequence of a String containing only vowels
- Longest Subsequence of a String containing only Consonants
- Sub-strings of length K containing same character
- Generate a string which differs by only a single character from all given strings
- Find the count of M character words which have at least one character repeated
- Count of strings possible by replacing two consecutive same character with new character
- Print Kth character in sorted concatenated substrings of a string
- Maximize partitions such that no two substrings have any common character
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.