Given a balanced parentheses string s, return the score of the string.
The score of a balanced parentheses string is based on the following rule:
"()" has score 1.AB has score A + B, where A and B are balanced parentheses strings.(A) has score 2 * A, where A is a balanced parentheses string.
Example 1:
Input: s = "()" Output: 1
Example 2:
Input: s = "(())" Output: 2
Example 3:
Input: s = "()()" Output: 2
Constraints:
2 <= s.length <= 50s consists of only '(' and ')'.s is a balanced parentheses string.This approach leverages a stack to manage the scores of the balanced parentheses string. As we iterate through the string:
At the end of the iteration, the top of the stack will contain the total score.
The C solution utilizes a simple stack array to keep track of scores at each level. As we parse the string, we push zero onto the stack for each '('. When encountering a ')', the score is calculated and added to the top of the stack. This method ensures that nested structures are calculated accurately by collapsing scores upwards through multiplication and addition.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(n), due to the stack usage that can store one element per character in the worst case.
This approach iteratively computes the score by tracking the depth of parentheses:
In C, this iterative approach uses an array to track scores at different depths. It handles the transition from '(' to ')' by either recognizing single pairs or multiplying for nested structures. This approach exploits direct index manipulation for score calculations.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), dictated by the string length.
Space Complexity: O(1), since the depth array size is fixed by constraint.
| Approach | Complexity |
|---|---|
| Stack-Based Solution | Time Complexity: O(n), where n is the length of the string. |
| Iterative with Depth Tracking | Time Complexity: O(n), dictated by the string length. |
Generate Parentheses - Stack - Leetcode 22 • NeetCode • 436,448 views views
Watch 9 more video solutions →Practice Score of Parentheses with our built-in code editor and test cases.
Practice on FleetCode