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:
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 having the most frequent character in the string as first character
- Count substrings that starts with character X and ends with character Y
- Count of substrings having all distinct characters
- Count ways to split a Binary String into three substrings having equal count of zeros
- Number of substrings with count of each character as k
- Count of substrings which contains a given character K times
- Count of substrings containing only the given character
- Count substrings with each character occurring at most k times
- Count substrings of same length differing by a single character from two given strings
- Count of K-size substrings having palindromic permutations
- Count of Substrings with at least K pairwise Distinct Characters having same Frequency
- Count of Substrings having Sum equal to their Length
- Count of binary strings of length N having equal count of 0's and 1's and count of 1's ≥ count of 0's in each prefix substring
- Minimize length of Substrings containing at least one common Character
- Maximize partitions such that no two substrings have any common character
- Print Kth character in sorted concatenated substrings of a string
- Map every character of one string to another such that all occurrences are mapped to the same character
- Replace all occurrences of character X with character Y in given string
- Find the count of M character words which have at least one character repeated
- Generate a String of having N*N distinct non-palindromic Substrings
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.