Given a string str consisting of pairs of balanced parentheses, the task is to calculate the score of the given string based on the following rules:
- “()” has a score of 1.
- “x y” has a score of x + y where x and y are individual pairs of balanced parentheses.
- “(x)” has a score twice of x (i.e), 2 * score of x.
Input: str = “()()”
Explanation: There are are two individual psirs of balanced parenthesis “() ()”. Therefore, score = score of “()” + score of “()” = 1 + 1 = 2
Input: str = “(())”
Explanation: Since the input is of the form “(x)”, the total score = 2 * score of “()” = 2 * 1 = 2
Approach: The problem can be solved using Stack. The idea is to iterate over the characters of the string. For every ith character check if the character is ‘(‘ or not. If found to be true, then insert the character into the stack. Otherwise, calculate the score of the inner parenthesis and insert double of the score into the stack. Follow the steps below to solve the problem:
- Initialize a stack to store the current traversed character or the score of inner balanced parenthesis.
- Iterate over the characters of the string, str. For every ith character check the following conditions:
- If the current character is ‘(‘ or not. If found to be true, then push the current character into the stack.
- Otherwise, check if the top element of the stack is ‘(‘ or not. If found to be true, then insert “1” into the stack which represents the score of the inner balanced parenthesis.
- Otherwise, double the top element of the stack and push the obtained value into the stack.
- Finally, print the total score obtained.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.