Calculate score of parentheses from a given string | C ++ program for the above approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void scoreOfParentheses ( string s ) { stack < int > stack ; stack . push ( 0 ) ; for ( char c : s ) { if ( c == ' ( ' ) stack . push ( 0 ) ; else { int tmp = stack . top ( ) ; stack . pop ( ) ; int val = 0 ; if ( tmp > 0 ) val = tmp * 2 ; else val = 1 ; stack . top ( ) += val ; } } cout << stack . top ( ) ; } int main ( ) { string S = " ( ( ) ( ( ) ) ) " ; scoreOfParentheses ( S ) ; return 0 ; }