Given a string str and a character K, the task is to find the count of all the substrings of str that contain the character K.
Input: str = “geeks”, K = ‘g’
“g”, “ge”, “gee”, “geek” and “geeks” are the valid substrings.
Input: str = “geeksforgeeks”, K = ‘k’
Naive approach A simple approach will be to find all the substrings having character K of the given string and return the count;
Efficient approach: For every index i in the string, find the first index j such that i ≤ j and str[j] = K. Now, the substrings str[i…j], str[i…j + 1], str[i…j + 2], …, str[i…n – 1] will all contain the character K at least once. The approach seems to be O(n2) at first but the index j will not be calculated again for every index i, j will be a valid index for all the values of i less than j.
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
- Find the count of M character words which have at least one character repeated
- Count substrings that contain all vowels | SET 2
- Count substrings with same first and last characters
- Count of substrings of a binary string containing K ones
- Count of total anagram substrings
- Count Substrings with equal number of 0s, 1s and 2s
- Find the count of substrings in alphabetic order
- Count number of distinct substrings of a given length
- Count of Palindromic substrings in an Index range
- Count number of substrings with exactly k distinct characters
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.