Compute the score of a balanced parentheses string using the rule that () = 1 and concatenation/nesting combine scores.
Score of Parentheses
You are given a balanced parentheses string s consisting only of '(' and ')'.
Define the score of a balanced string as follows:
"()"has score1ABhas scorescore(A) + score(B), whereAandBare balanced strings(A)has score2 * score(A), whereAis a balanced string
Return the score of s.
A string is balanced if it is empty or can be built from the rules above.
Input Format
- A single string
s scontains only'('and')'sis guaranteed to be balanced
Output Format
- Return one integer: the score of the parentheses string
Constraints
- The string is balanced
- Length is at least 2
1 <= |s| <= 50in typical interview settings; exact platform limits may differ
Example 1
Input
s = "()"
Output
1
Explanation
The smallest balanced pair has score 1.
Example 2
Input
s = "(())"
Output
2
Explanation
The inner "()" scores 1, and wrapping it in parentheses doubles the score to 2.
Show 1 more example
Example 3
Input
s = "()()"
Output
2
Explanation
The string is a concatenation of two balanced parts: 1 + 1 = 2.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.