Loading content...
You are given a string s consisting exclusively of well-matched opening and closing brackets ( and ). Your task is to compute and return the total score of the string based on the following recursive scoring rules:
Base Unit Rule: The simplest unit () has a score of exactly 1.
Concatenation Rule: When two balanced bracket sequences A and B appear adjacently as AB, their combined score equals the sum of their individual scores: score(A) + score(B).
Nesting Rule: When a balanced bracket sequence A is wrapped inside another pair of brackets to form (A), the resulting score is double the score of A: 2 × score(A).
The input string is guaranteed to be a valid, fully balanced bracket expression—every opening bracket has a corresponding closing bracket in the correct order.
Intuition Behind the Scoring
Think of brackets as representing nested function calls or hierarchical structures. The deeper a structure is nested, the more "weight" or "importance" it carries. The base case () represents a single unit of work. Nesting doubles the value (like interest compounding), while concatenation adds values together (like summing independent operations). This scoring system elegantly captures the depth-based weighting common in tree and recursion problems.
s = "()"1This is the base case—a single, minimal balanced pair. According to the base unit rule, '()' has a score of exactly 1.
s = "(())"2Here, the inner '()' has a score of 1. When wrapped inside outer brackets to form '(())', the nesting rule applies: the score is doubled. Thus, the final score is 2 × 1 = 2.
s = "()()"2This expression consists of two adjacent '()' units. By the concatenation rule, we sum their scores: 1 + 1 = 2.
Constraints