Calculate score of parentheses from a given string | Java 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
import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static void scoreOfParentheses ( String s ) { Stack < Integer > stack = new Stack < > ( ) ; stack . push ( 0 ) ; for ( char c : 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 ) ; } } System . out . println ( stack . peek ( ) ) ; } public static void main ( String [ ] args ) { String S = " ( ( ) ( ( ) ) ) " ; scoreOfParentheses ( S ) ; } }