Score of Parentheses

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`.

30:00

Score of Parentheses
medium
Free written solution
Topics
Companies

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.

Example 1:
Input: {"s":"()"}
Output: 1
Constraints:
  • 2≤s.length≤502 \leq \text{s.length} \leq 50

  • s consists of only '(' and ')'.

  • s is a balanced parentheses string.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"()"}

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

0

closing rule

On ')': pop the inner score v, then add max(2 * v, 1) to the level below.

Variables
VariableValue
cnull
depth0
stack[0]
DepthFunction Call
Stack empty
0/4