π One-stop destination for all your technical interview Preparation π
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:
(
, we push 0 to the stack.)
, pop call 0βs and multiple the result with 2, also if there is only one () then result will become 0 so store val as max(1, 2*val)
, push the result to the stack.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;
}
};
Intuition
Algorithm
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;
}
};
The key idea is that:
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 ( ( ) )
+ ( ( ( ) ) )
.