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
function Balanced_Substring ( str , n ) { let ans = 0 ; let arr = new Array ( n / 2 + 1 ) . fill ( 0 ) ; let d = 0 ; for ( let i = 0 ; i < n ; i ++ ) { if ( str [ i ] == ' ' ) d ++ ; else { if ( d == 1 ) { for ( let j = 2 ; j <= parseInt ( n / 2 ) + 1 && arr [ j ] != 0 ; j ++ ) arr [ j ] = 0 ; } ++ ans ; ans += arr [ d ] ; arr [ d ] ++ ; d -- ; } } return ans ; } let str = " " ; let n = str . length ; document . write ( Balanced_Substring ( str , n ) ) ;