Open In App

Calculate score of parentheses from a given string

Last Updated : 10 Jun, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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:
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: 6
Explanation: 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:
  • 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++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate the score
// of the parentheses using stack
void 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 Code
int main()
{
    string S = "(()(()))";
    scoreOfParentheses(S);
 
    return 0;
}


Java




// Java program for the above approach
import 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.


Python3




# Python 3 program for the above approach
 
# Function to calculate the score
# of the parentheses using stack
def 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 Code
if __name__ == '__main__':
    S = "(()(()))"
    scoreOfParentheses(S)
     
    # This code is contributed by bgangwar59.


C#




// C# program for the above approach
using 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


Javascript




<script>
 
// JavaScript program for the above approach
 
// Function to calculate the score
// of the parentheses using stack
function 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 Code
var S = "(()(()))";
scoreOfParentheses(S);
 
 
</script>


 
 

Output: 

6

 

Time Complexity: O(N)
Auxiliary Space: O(N) 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads