30:00
Given a balanced parentheses string s, return its score. "()" scores 1, AB scores A + B for balanced strings A and B, and (A) scores 2 * A.
s
"()"
AB
A + B
A
B
(A)
2 * A
2≤s.length≤502 \leq \text{s.length} \leq 502≤s.length≤50
s consists of only '(' and ')'.
'('
')'
s is a balanced parentheses string.
Run code to see results.
Start with stack = [0]: one running total for the outermost level, which will hold the final score.
s, colored by depth
0
1
Under each closed ')' is what its pair added to the level around it.
stack of running scores (top = innermost)
outer level
closing rule
On ')': pop the inner score v, then add max(2 * v, 1) to the level below.
Score a balanced parentheses string where () is 1, two balanced strings side by side add, and wrapping a balanced string in parentheses doubles it.