Nested Bracket Score Calculation
Implement scoreOfBrackets
Given a balanced bracket string
s containing only '(' and ')', compute its score using these rules: "()" scores 1; two concatenated pieces AB score the sum of their individual scores; and a piece wrapped as (A) scores twice ADoubling on NestingWrapping any scored piece A in one more layer of parentheses always doubles its score — that's the entire rule that turns "how deeply nested" into "what power of 2 to multiply by." — nesting doubles whatever score is inside.
Since nesting always doubles and concatenation always adds, every innermost "()" pair's ultimate contribution to the total is exactly 2^d, where d is how many enclosing pairs wrap around it. A single pass with a stack computes this without ever explicitly calculating a power of 2: push a fresh 0 for every new level opened, and whenever a level closes, fold its score into the level directly beneath it — doubling it first if it wasn't just a bare pair. By the time the string is fully consumed, the bottom of the stack holds the total.
Example 1:
Input: s = "(())()"
Output: 3
Example 2:
Input: s = "((()))"
Output: 4
Example 3:
Input: s = "()(())"
Output: 3
+ 6 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ s.length ≤ 20 - ●
s is a balanced bracket string consisting only of '(' and ')'
s =
(())()