Given a string str of n lowercase characters, the task is to count the number of substrings of str starting with character X and ending with character Y.
Input: str = "abbcaceghcak" x = 'a', y = 'c' Output: 5 abbc, abbcac, ac, abbcaceghc, aceghc Input: str = "geeksforgeeks" x = 'g', y = 'e' Output: 6
- Initialize two counters i.e. tot_count to count the total number of substrings and count_x to count the number of strings that start with X.
- Start traversing the string.
- If the current character is X then increment the count of count_x.
- If the current character is Y, it means a string ends at Y so increment the count of tot_count i.e.
tot_count = tot_count + count_x
It means that if there exists a Y then it will make a substring with all the X occurs before Y in the string. So, add the count of X to the total count.
- Return total count.
Below is the implementation of above approach:
Count = 5
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.
- Number of strings which starts and ends with same character after rotations
- Longest subsequence possible that starts and ends with 1 and filled with 0 in the middle
- Find if a string starts and ends with another given string
- Maximum length palindromic substring such that it starts and ends with given char
- Longest substring that starts with X and ends with Y
- Build a DFA to accept Binary strings that starts or ends with "01"
- Ways to split string such that each partition starts with distinct character
- Program to build DFA that starts and end with 'a' from input (a, b)
- Number of substrings with count of each character as k
- Count substrings with each character occurring at most k times
- Count of substrings which contains a given character K times
- Count all substrings having character K
- Count of substrings containing only the given character
- Check if a number starts with another number or not
- Program to build a DFA that checks if a string ends with "01" or "10"
- Check if a number ends with another number or not
- Check whether the binary equivalent of a number ends with given string or not
- Count ways to split a Binary String into three substrings having equal count of zeros
- Print Kth character in sorted concatenated substrings of a string
- Minimize length of Substrings containing at least one 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.