Calculate score of parentheses from a given string - GeeksforGeeks

10 Jun, 2021
Given string str of length N, consisting of pairs of balanced parentheses, the task is to calculate the score of the given string based on the given rules:
“()” has a score of 1.
“a b” has a score of a + b, where a and b are individual pairs of balanced parentheses.
“(a)” has a score twice of a i.e., the score is 2 * score of a.
Examples:
Input: str = “()()” Output: 2 Explanation: The string str is of the form “ab”, that makes the total score = (score of a) + (score of b) = 1 + 1 = 2.
Input: str = “(()(()))”Output: 6Explanation: The string str is of the form “(a(b))” which makes the total score = 2 * ((score of a) + 2*(score of b)) = 2*(1 + 2*(1)) = 6.
Tree-based Approach: Refer to the previous post of this article for the tree-based approach. Time Complexity: O(N)Auxiliary Space: O(N)
Stack-based Approach: The idea is to traverse the string and while traversing the string str, if the parenthesis ‘)’ is encountered, then calculate the score of this pair of parentheses. Follow the steps below to solve the problem:
Initialize a stack, say S, to keep track of the score and initially push 0 into the stack.
Traverse the string str using the variable i and perform the following steps:If the value of str[i] is equal to ‘(‘, push 0 to the stack S.Otherwise, perform the following steps:Store the top of the stack S in a variable, say temp, and pop the element from the top of the stack.If the value of temp is non-zero, then inner parentheses exist. Add 2 * temp to the top of the stack. Otherwise, add 1 to the top of the stack.
If the value of str[i] is equal to ‘(‘, push 0 to the stack S.
Otherwise, perform the following steps:Store the top of the stack S in a variable, say temp, and pop the element from the top of the stack.If the value of temp is non-zero, then inner parentheses exist. Add 2 * temp to the top of the stack. Otherwise, add 1 to the top of the stack.
Store the top of the stack S in a variable, say temp, and pop the element from the top of the stack.
If the value of temp is non-zero, then inner parentheses exist. Add 2 * temp to the top of the stack. Otherwise, add 1 to the top of the stack.
After completing the above steps, print the value of the top of the stack as the result.
Below is the implementation of the above approach: 
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to calculate the score// of the parentheses using stackvoid scoreOfParentheses(string s){    // To keep track of the score    stack<int> stack;     // Initially, push 0 to stack    stack.push(0);     // Traverse the string s    for (char c : s) {         // If '(' is encountered,        // then push 0 to stack        if (c == '(')            stack.push(0);         // Otherwise        else {             // Balance the last '(', and store            // the score of inner parentheses            int tmp = stack.top();            stack.pop();             int val = 0;             // If tmp is not zero, it means            // inner parentheses exists            if (tmp > 0)                val = tmp * 2;             // Otherwise, it means no            // inner parentheses exists            else                val = 1;             // Pass the score of this level            // to parent parentheses            stack.top() += val;        }    }     // Print the score    cout << stack.top();} // Driver Codeint main(){    string S = "(()(()))";    scoreOfParentheses(S);     return 0;}
// Java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; class GFG {   // Function to calculate the score  // of the parentheses using stack  static void scoreOfParentheses(String s)  {         // To keep track of the score    Stack<Integer> stack = new Stack<>();     // Initially, push 0 to stack    stack.push(0);     // Traverse the string s    for (char c : s.toCharArray()) {       // If '(' is encountered,      // then push 0 to stack      if (c == '(')        stack.push(0);       // Otherwise      else {         // Balance the last '(', and store        // the score of inner parentheses        int tmp = stack.pop();         int val = 0;         // If tmp is not zero, it means        // inner parentheses exists        if (tmp > 0)          val = tmp * 2;         // Otherwise, it means no        // inner parentheses exists        else          val = 1;         // Pass the score of this level        // to parent parentheses        stack.push(stack.pop() + val);      }    }     // Print the score    System.out.println(stack.peek());  }   // Driver code  public static void main(String[] args)  {     String S = "(()(()))";     // Function call    scoreOfParentheses(S);  }} // This code is contributed by Kingash.
# Python 3 program for the above approach # Function to calculate the score# of the parentheses using stackdef scoreOfParentheses(s):       # To keep track of the score    stack = []     # Initially, push 0 to stack    stack.append(0)     # Traverse the string s    for c in s:               # If '(' is encountered,        # then push 0 to stack        if (c == '('):            stack.append(0)         # Otherwise        else:                       # Balance the last '(', and store            # the score of inner parentheses            tmp = stack[len(stack) - 1]            stack = stack[:-1]             val = 0             # If tmp is not zero, it means            # inner parentheses exists            if (tmp > 0):                val = tmp * 2             # Otherwise, it means no            # inner parentheses exists            else:                val = 1             # Pass the score of this level            # to parent parentheses            stack[len(stack) - 1] += val     # Print the score    print(stack[len(stack) - 1]) # Driver Codeif __name__ == '__main__':    S = "(()(()))"    scoreOfParentheses(S)         # This code is contributed by bgangwar59.
// C# program for the above approachusing System;using System.Collections.Generic;public class GFG{   // Function to calculate the score  // of the parentheses using stack  static void scoreOfParentheses(String s)  {         // To keep track of the score    Stack<int> stack = new Stack<int>();     // Initially, push 0 to stack    stack.Push(0);     // Traverse the string s    foreach (char c in s.ToCharArray()) {       // If '(' is encountered,      // then push 0 to stack      if (c == '(')        stack.Push(0);       // Otherwise      else {         // Balance the last '(', and store        // the score of inner parentheses        int tmp = stack.Pop();         int val = 0;         // If tmp is not zero, it means        // inner parentheses exists        if (tmp > 0)          val = tmp * 2;         // Otherwise, it means no        // inner parentheses exists        else          val = 1;         // Pass the score of this level        // to parent parentheses        stack.Push(stack.Pop() + val);      }    }     // Print the score    Console.WriteLine(stack.Peek());  }   // Driver code  public static void Main(String[] args)  {     String S = "(()(()))";     // Function call    scoreOfParentheses(S);  }} // This code is contributed by 29AjayKumar
<script> // JavaScript program for the above approach // Function to calculate the score// of the parentheses using stackfunction scoreOfParentheses(s){    // To keep track of the score    var stack = [];     // Initially, push 0 to stack    stack.push(0);     // Traverse the string s    s.split('').forEach(c => {                  // If '(' is encountered,        // then push 0 to stack        if (c == '(')            stack.push(0);         // Otherwise        else {             // Balance the last '(', and store            // the score of inner parentheses            var tmp = stack[stack.length-1];            stack.pop();             var val = 0;             // If tmp is not zero, it means            // inner parentheses exists            if (tmp > 0)                val = tmp * 2;             // Otherwise, it means no            // inner parentheses exists            else                val = 1;             // Pass the score of this level            // to parent parentheses            stack[stack.length-1] += val;        }    });     // Print the score    document.write( stack[stack.length-1]);} // Driver Codevar S = "(()(()))";scoreOfParentheses(S);  </script>
  
6
 
Time Complexity: O(N)Auxiliary Space: O(N) 
bgangwar59
Kingash
29AjayKumar
rrrtnx
cpp-stack
Parentheses-Problems
Mathematical
Stack
Strings
Strings
Mathematical
Stack
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Merge two sorted arrays
Prime Numbers
Modulo Operator (%) in C/C++ with Examples
Find all factors of a natural number | Set 1
Program to find sum of elements in a given array
Stack Data Structure (Introduction and Program)
Stack Class in Java
Stack in Python
Inorder Tree Traversal without Recursion
Queue using Stacks