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
using System ; using System . Collections . Generic ; class GFG { static long scoreOfParentheses ( String S ) { Stack < String > s = new Stack < String > ( ) ; int i = 0 ; long ans = 0 ; while ( i < S . Length ) { if ( S [ i ] == ' ( ' ) s . Push ( " ( " ) ; else { if ( s . Peek ( ) == " ( " ) { s . Pop ( ) ; s . Push ( "1" ) ; } else { long count = 0 ; while ( s . Peek ( ) != " ( " ) { count += Int32 . Parse ( s . Peek ( ) ) ; s . Pop ( ) ; } s . Pop ( ) ; s . Push ( String . Join ( " " , 2 * count ) ) ; } } i ++ ; } while ( s . Count != 0 ) { ans += Int32 . Parse ( s . Peek ( ) ) ; s . Pop ( ) ; } return ans ; } public static void Main ( String [ ] args ) { String S1 = " ( ( ) ( ( ) ) ) " ; Console . Write ( scoreOfParentheses ( S1 ) + " STRNEWLINE " ) ; } }