Tuesday, 19 Oct 2021

# Calculate score of parentheses from a given string

Calculate score of parentheses from a given string
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:

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++

#include
using namespace std;

void scoreOfParentheses(string s)
{

stack stack;

stack.push(0);

for (char c : s) {

if (c == ‘(‘)
stack.push(0);

else {

int tmp = stack.top();
stack.pop();

int val = 0;

if (tmp > 0)
val = tmp * 2;

else
val = 1;

stack.top() += val;
}
}

cout