Given a string str consisting of lowercase English alphabets, the task is to find the count of substrings that start with “geeks” and end with “for”.
Input: str = “geeksforgeeksisforgeeks”
“geeksfor”, “geeksforgeeksisfor” and “geeksisfor”
are the only valid substrings.
Input: str = “geeksforgeeks”
Naive approach: First set the counter to 0 then iterate over the string and whenever the substring “geeks” is encountered, from the very next indices again iterate over the string and try to find the substring “for”. If “for” is present then increment the counter and finally print it.
Efficient approach: Set two counter for the substrings “geeks” and “for”, say c1 and c2. On iterating, whenever the substring “geeks” is encountered, increment c1 and whenever “for” is encountered, set c2 = c2 + c1. This is because every occurrence of “geeks” will make a valid substring with the current found “for”. Finally print c2.
Below is the implementation of the above approach:
- Given a binary string, count number of substrings that start and end with 1.
- Different substrings in a string that start and end with given strings
- Number of substrings with length divisible by the number of 1's in it
- Number of substrings of a string
- Number of substrings divisible by 8 but not by 3
- Number of substrings of one string present in other
- Sum of all substrings of a string representing a number | Set 1
- Number of even substrings in a string of digits
- Number of balanced parenthesis substrings
- Number of substrings with count of each character as k
- Count Substrings with equal number of 0s, 1s and 2s
- Count number of substrings with exactly k distinct characters
- Count number of distinct substrings of a given length
- Count number of substrings with numeric value greater than X
- Number of substrings divisible by 6 in a string of integers