Problem Description
Given a balanced parentheses string s, calculate the score of the string based on these rules:
- "()" has score 1.
- For two balanced strings A and B, the score of AB is A + B.
- For a balanced string A enclosed in parentheses "(A)", the score is 2 * A.
Key Insights
- Use a stack to process the parentheses structure.
- When encountering a closing parenthesis, check if it directly forms "()", assign score 1; otherwise, accumulate the inner score.
- Multiply the accumulated score by 2 when a nested structure is detected.
- The algorithm processes the string in one pass, handling nesting and direct pairs efficiently.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the string, because each character is processed once. Space Complexity: O(n), for the stack used in worst-case scenarios with nested parentheses.
Solution
Utilize a stack to keep track of intermediate scores. When encountering an opening parenthesis '(', push a marker (or a 0) onto the stack to indicate the start of a new sub-expression. When you encounter a closing parenthesis ')', pop values from the stack until you reach the marker:
- If the marker is immediately encountered, it means the parentheses form "()", so assign a score of 1.
- Otherwise, the popped values represent the score inside a nested structure; multiply it by 2 for the current level. Push the computed score back onto the stack. Finally, sum all values in the stack to get the final score.