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 score1
. -
AB
has scoreA + B
, whereA
andB
are balanced parentheses strings. -
(A)
has score2 * A
, whereA
is a balanced parentheses string.
Example 1:
Input: s = "()"
Output: 1
Example 2:
Input: s = "(())"
Output: 2
Example 3:
Input: s = "()()"
Output: 2
Constraints:
2 <= s.length <= 50
-
s
consists of only'('
and')'
. -
s
is a balanced parentheses string.
Solutions
Solution 1
Intuition
- store the base grade 0 to stack
- if we find another
(
, we just need to got the top grade and check its value- if it is 0, so we got 1 and put it back to top
- if it is bigger than 0, we need to double it
- 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();
}
};
Complexity
- Time: O(n)
- Space: O(n)
Top comments (0)