Given a balanced parenthesis string which consists of ‘(‘ and ‘)‘. The task is to find the number of balanced parenthesis substrings in the given string
Input : str = “()()()”
Output : 6
(), (), (), ()(), ()(), ()()()
Input : str = “(())()”
Output : 4
(), (()), (), (())()
Let us assume that whenever we encounter with opening bracket the depth increases by one and with a closing bracket the depth decreases by one. Whenever we encounter the closing bracket increase our required answer by one and then increment our required answer by the already formed balanced substrings at this depth.
Below is the implementation of the above approach :
Time complexity : O(N)
- Reverse substrings between each pair of parenthesis
- InfyTQ 2019 : Find the position from where the parenthesis is not balanced
- Number of substrings divisible by 8 but not by 3
- Number of substrings of a string
- Number of balanced bracket subsequence of length 2 and 4
- Number of even substrings in a string of digits
- Sum of all substrings of a string representing a number | Set 1
- Number of substrings with count of each character as k
- Number of substrings of one string present in other
- Count Substrings with equal number of 0s, 1s and 2s
- Number of substrings that start with "geeks" and end with "for"
- Minimum number of additons to make the string balanced
- Number of ways to partition a string into two balanced subsequences
- Count number of substrings with exactly k distinct characters
- Count number of substrings with numeric value greater than X
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.