Calculate score of a string consisting of balanced parentheses | Java 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
import java . util . * ; class GFG { static long scoreOfParentheses ( String S ) { Stack < String > s = new Stack < > ( ) ; int i = 0 ; long ans = 0 ; while ( i < S . length ( ) ) { if ( S . charAt ( i ) == ' ( ' ) s . add ( " ( " ) ; else { if ( s . peek ( ) == " ( " ) { s . pop ( ) ; s . add ( "1" ) ; } else { long count = 0 ; while ( s . peek ( ) != " ( " ) { count += Integer . parseInt ( s . peek ( ) ) ; s . pop ( ) ; } s . pop ( ) ; s . add ( String . valueOf ( 2 * count ) ) ; } } i ++ ; } while ( ! s . isEmpty ( ) ) { ans += Integer . parseInt ( s . peek ( ) ) ; s . pop ( ) ; } return ans ; } public static void main ( String [ ] args ) { String S1 = " ( ( ) ( ( ) ) ) " ; System . out . print ( scoreOfParentheses ( S1 ) + "NEW_LINE"); } }