Leetcode 856: Score of Parentheses

grid47
grid47
Exploring patterns and algorithms
Aug 13, 2024 5 min read

Given a balanced parentheses string, calculate the score of the string. The score is computed as follows:

  1. The score of ‘()’ is 1.
  2. For a concatenation of two balanced parentheses strings, AB, the score is the sum of their individual scores (A + B).
  3. For a balanced parentheses string wrapped in another pair of parentheses, (A), the score is twice the score of A (2 * A).
Problem
Approach
Steps
Complexity
Input: The input consists of a string s, which is a balanced parentheses string composed of only '(' and ')'. The length of the string is between 2 and 50 characters.
Example: Input: s = "(()())"
Constraints:
• 2 <= s.length <= 50
• s consists of only '(' and ')'.
• s is guaranteed to be a balanced parentheses string.
Output: Return the score of the given balanced parentheses string according to the rules defined above.
Example: Output: 6
Constraints:
Goal: The goal is to compute the score of a balanced parentheses string by applying the given rules to the input string.
Steps:
• Step 1: Initialize a stack to keep track of the scores for different parts of the string.
• Step 2: Iterate over the string. For every opening parenthesis, push the current score onto the stack and reset the score for the new section.
• Step 3: For each closing parenthesis, calculate the score based on the nested structure and update the score by applying the rule: max(2 * score, 1).
• Step 4: Return the final score.
Goal: Ensure that the string is balanced and only contains '(' and ')'.
Steps:
• The input string is guaranteed to be balanced.
Assumptions:
• The input string is always valid and balanced.
Input: Input: s = "(()())"
Explanation: In this example, the first pair '()' gives a score of 1. The second pair '()' gives another score of 1. The nested structure '(())' gives a score of 2. Therefore, the total score is 6 (1 + 1 + 2 + 2).

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus