DEV Community

Wenqi Jiang
Wenqi Jiang

Posted on

856. Score of Parentheses

Description

Given a balanced parentheses string s, return the score of the string.

The score of a balanced parentheses string is based on the following rule:

  • "()" has score 1.
  • AB has score A + B, where A and B are balanced parentheses strings.
  • (A) has score 2 * A, where A is a balanced parentheses string.

Example 1:

Input: s = "()"
Output: 1
Enter fullscreen mode Exit fullscreen mode

Example 2:

Input: s = "(())"
Output: 2
Enter fullscreen mode Exit fullscreen mode

Example 3:

Input: s = "()()"
Output: 2
Enter fullscreen mode Exit fullscreen mode

Constraints:

  • 2 <= s.length <= 50
  • s consists of only '(' and ')'.
  • s is a balanced parentheses string.

Solutions

Solution 1

Intuition

  1. store the base grade 0 to stack
  2. if we find another ( , we just need to got the top grade and check its value
    1. if it is 0, so we got 1 and put it back to top
    2. if it is bigger than 0, we need to double it
  3. return the top

Code

class Solution {
public:
    int scoreOfParentheses(string s) {
        stack<int> stk;
        stk.push(0);
        for (char c : s) {
            if (c == '(') {
                stk.push(0);
            } else {
                int g = stk.top();
                stk.pop();
                if (g == 0) {
                    g = 1;
                } else {
                    g *= 2;
                }
                stk.top() += g;
            }
        }
        return stk.top();
    }
};
Enter fullscreen mode Exit fullscreen mode

Complexity

  • Time: O(n)
  • Space: O(n)

Top comments (0)