Calculate score of a string consisting of balanced parentheses | Function to calculate score of parentheses ; Stores index of character of string ; Stores total scores obtained from the string ; Iterate over characters of the string ; If s [ i ] is ' ( ' ; If top element of stack is ' ( ' ; Stores score of inner parentheses ; Calculate score of inner parentheses ; Update count ; Pop from stack ; Insert score of inner parentheses ; Update i ; Calculate score of the string ; Update ans ; Driver Code
function scoreOfParentheses ( S ) { var s = [ ] ; var i = 0 ; var ans = 0 ; while ( i < S . length ) { if ( S [ i ] == ' ' ) s . push ( " " ) ; else { if ( s [ s . length - 1 ] == " " ) { s . pop ( ) ; s . push ( " " ) ; } else { var count = 0 ; while ( s [ s . length - 1 ] != " " ) { count += parseInt ( s [ s . length - 1 ] ) ; s . pop ( ) ; } s . pop ( ) ; s . push ( ( 2 * count ) . toString ( ) ) ; } } i ++ ; } while ( s . length != 0 ) { ans += parseInt ( s [ s . length - 1 ] ) ; s . pop ( ) ; } return ans ; } var S1 = " " ; document . write ( scoreOfParentheses ( S1 ) ) ;