Calculate score of a string consisting of balanced parentheses | C ++ program to implement the above approach ; 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
#include <iostream> NEW_LINE #include <stack> NEW_LINE using namespace std ; long long scoreOfParentheses ( string S ) { stack < string > s ; int i = 0 ; long long ans = 0 ; while ( i < S . length ( ) ) { if ( S [ i ] == ' ( ' ) s . push ( " ( " ) ; else { if ( s . top ( ) == " ( " ) { s . pop ( ) ; s . push ( "1" ) ; } else { long long count = 0 ; while ( s . top ( ) != " ( " ) { count += stoi ( s . top ( ) ) ; s . pop ( ) ; } s . pop ( ) ; s . push ( to_string ( 2 * count ) ) ; } } i ++ ; } while ( ! s . empty ( ) ) { ans += stoi ( s . top ( ) ) ; s . pop ( ) ; } return ans ; } int main ( ) { string S1 = " ( ( ) ( ( ) ) ) " ; cout << scoreOfParentheses ( S1 ) << endl ; return 0 ; }