medium +20 pts

Score of Parentheses

Compute the score of a balanced parentheses string using stack-based rules.

Given a balanced parentheses string `s` consisting only of characters '(' and ')', compute its score according to the following rules: - `()` has score 1. - `AB` (concatenation of two balanced strings) has score `score(A) + score(B)`. - `(A)` has score `2 * score(A)`. Implement the function `score_of_parentheses(s: str) -> int` that returns the score of the input string. The input string is guaranteed to be a balanced parentheses string (i.e., valid).

Constraints

1 <= len(s) <= 50 `s` is a balanced parentheses string containing only '(' and ')'. The score of the string fits within a 32-bit integer.

Example

>>> score_of_parentheses("()")
1
>>> score_of_parentheses("(())")
2
>>> score_of_parentheses("()()")
2
>>> score_of_parentheses("(()(()))")
6
20 points ~20 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use a stack to keep track of the current score at each nesting level.
When you see '(', push the current score onto the stack and reset it to 0.
When you see ')', the score for the just-ending group is max(1, 2 * current). Add it to the parent level from the stack.
At the end, the total score is at the top of the stack.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.