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:
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Count substrings that starts with character X and ends with character Y
- Number of substrings with count of each character as k
- Count of substrings which contains a given character K times
- 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 with same first and last characters
- Count substrings that contain all vowels | SET 2
- Count of total anagram substrings
- Count Substrings with equal number of 0s, 1s and 2s
- Count of substrings of a binary string containing K ones
- Count of all unique substrings with non-repeating characters
- Count all Prime Length Palindromic Substrings
- 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.