Number of balanced parenthesis substrings | Function to find number of balanced parenthesis sub strings ; To store required answer ; Vector to stores the number of balanced brackets at each depth . ; d stores checks the depth of our sequence For example level of ( ) is 1 and that of ( ( ) ) is 2. ; If open bracket increase depth ; If closing bracket ; Return the required answer ; Driver code ; Function call
def Balanced_Substring ( s , n ) : NEW_LINE INDENT ans = 0 ; NEW_LINE arr = [ 0 ] * ( int ( n / 2 ) + 1 ) ; NEW_LINE d = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == ' ( ' ) : NEW_LINE INDENT d += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT if ( d == 1 ) : NEW_LINE INDENT j = 2 NEW_LINE while ( j <= n // 2 + 1 and arr [ j ] != 0 ) : NEW_LINE INDENT arr [ j ] = 0 NEW_LINE DEDENT DEDENT ans += 1 ; NEW_LINE ans += arr [ d ] ; NEW_LINE arr [ d ] += 1 ; NEW_LINE d -= 1 ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT s = " ( ) ( ) ( ) " ; NEW_LINE n = len ( s ) ; NEW_LINE print ( Balanced_Substring ( s , n ) ) ; NEW_LINE