Score of Parentheses - Problem
Given a balanced parentheses string s, calculate its score based on a simple scoring system that rewards proper nesting.
The Scoring Rules:
()has a score of 1- Concatenated strings
ABhave score A + B, where A and B are balanced parentheses strings - Nested strings
(A)have score 2 * A, where A is a balanced parentheses string
For example, "()()" scores 2 (1 + 1), while "(())" scores 2 (2 * 1). The deeper the nesting, the higher the exponential growth!
Your task: Return the total score of the given balanced parentheses string.
Input & Output
example_1.py โ Basic nesting
$
Input:
"(())"
โบ
Output:
2
๐ก Note:
The inner () scores 1 point. The outer parentheses double this score: 2 ร 1 = 2.
example_2.py โ Adjacent pairs
$
Input:
"()()"
โบ
Output:
2
๐ก Note:
Two adjacent () pairs, each scoring 1 point. Total: 1 + 1 = 2.
example_3.py โ Complex nesting
$
Input:
"(()())"
โบ
Output:
4
๐ก Note:
Inside the outer parentheses: () scores 1, () scores 1, so inner total is 1 + 1 = 2. The outer parentheses double this: 2 ร 2 = 4.
Constraints
- 1 โค s.length โค 50
- s consists of only '(' and ')' characters
- s is a balanced parentheses string
Visualization
Tap to expand
Understanding the Visualization
1
Identify the dolls
Each () pair represents a complete doll. Nested pairs represent dolls inside other dolls
2
Score innermost dolls
The smallest dolls () are worth 1 point each
3
Apply nesting multiplier
Each layer that wraps around doubles the inner value
4
Add adjacent values
Dolls sitting side by side contribute their values independently
Key Takeaway
๐ฏ Key Insight: Use a stack to track nesting levels and apply scoring rules in real-time, avoiding the need for complex recursive parsing!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code