Complete-Preparation

πŸŽ‰ One-stop destination for all your technical interview Preparation πŸŽ‰

View the Project on GitHub

856. Score of Parentheses 🌟🌟

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:

Using stack

code

class Solution {
public:
    int scoreOfParentheses(string s)
    {
        int cnt = 0;
        stack<int> st;
        for (auto c : s) {
            int val = 0;
            if (c == '(') {
                st.push(0);
            } else {
                while (st.top() != 0) {
                    val += st.top();
                    st.pop();
                }
                val = max(2*val, 1);
                st.pop();
                st.push(val);
            }
        }
        while (!st.empty()) {
            cnt += st.top();
            st.pop();
        }
        return cnt;
    }
};

Leetcode Approach 3: Count Cores

Intuition

Algorithm

Code

class Solution {
public:
    int scoreOfParentheses(string s)
    {
        int ans = 0, bal = 0;
        for (int i = 0; i < s.size(); ++i) {
            if (s[i] == '(') {
                bal++;
            } else {
                bal--;
                if (s[i-1] == '(')
                    ans += 1 << bal;
            }
        }
        return ans;
    }
};

kkzeng’s explanation:

The key idea is that:

  1. the balance tells you what β€œdepth” you are at since with each β€˜(β€˜ we are increasing the depth by 1 (kind of similar to the concept in Solution 2).
  2. the β€œcores” () are the only structure that provides value, the outer parentheses just add some multiplier to the cores. So we only need to be concerned with those. With those 2 ideas in mind, we are able to calculate how much the β€œcore” is worth directly without having to calculate substructures recursively and then apply multipliers.

E.g. For the example of ( ( ) ( ( ) ) ), with the stack method, we are calculating the inner structure ( ) ( ( ) ) first and then multiplying the score by 2. With the 3rd method, by knowing the depth of the core, we are actually performing this calculation ( ( ) ) + ( ( ( ) ) ).