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
using System ; using System . Collections . Generic ; public class GFG { static void scoreOfParentheses ( String s ) { Stack < int > stack = new Stack < int > ( ) ; stack . Push ( 0 ) ; foreach ( char c in s . ToCharArray ( ) ) { if ( c == ' ( ' ) stack . Push ( 0 ) ; else { int tmp = stack . Pop ( ) ; int val = 0 ; if ( tmp > 0 ) val = tmp * 2 ; else val = 1 ; stack . Push ( stack . Pop ( ) + val ) ; } } Console . WriteLine ( stack . Peek ( ) ) ; } public static void Main ( String [ ] args ) { String S = " ( ( ) ( ( ) ) ) " ; scoreOfParentheses ( S ) ; } }