Calculate score of parentheses from a given string | Function to calculate the score of the parentheses using stack ; To keep track of the score ; Initially , push 0 to stack ; Traverse the string s ; If ' ( ' is encountered , then push 0 to stack ; Otherwise ; Balance the last ' ( ' , and store the score of inner parentheses ; If tmp is not zero , it means inner parentheses exists ; Otherwise , it means no inner parentheses exists ; Pass the score of this level to parent parentheses ; Print the score ; Driver Code ; Function call
function scoreOfParentheses ( s ) { var stack = [ ] ; stack . push ( 0 ) ; s . split ( ' ' ) . forEach ( c => { if ( c == ' ' ) stack . push ( 0 ) ; else { var tmp = stack [ stack . length - 1 ] ; stack . pop ( ) ; var val = 0 ; if ( tmp > 0 ) val = tmp * 2 ; else val = 1 ; stack [ stack . length - 1 ] += val ; } } ) ; document . write ( stack [ stack . length - 1 ] ) ; } var S = " " ; scoreOfParentheses ( S ) ;