Given a balanced parentheses string S, you need to compute the score of the string based on the following rules:
() has a score of 1.AB has a score of A + B, where A and B are balanced parentheses strings.(A) has a score of 2 * A, where A is a balanced parentheses string.Input: S = "()"
Output: 1
Input: S = "(())"
Output: 2
Input: S = "()()"
Output: 2
Input: S = "(()(()))"
Output: 6
S?Let’s assume the string is always a valid balanced parentheses string and the length constraints are manageable within typical competitive programming limits.
Given the rules, we can use a stack-based approach to compute the score:
S:
'(', we push a marker (e.g., 0) onto the stack to denote the beginning of a new group.')', we:
A in the rule (A) (score is 2 * A).() with a score of 1.2 * A.The time complexity is O(n), where n is the length of the string S, since each character is processed a constant number of times (push and pop operations on the stack).
def scoreOfParentheses(s: str) -> int:
stack = []
for char in s:
if char == '(':
stack.append(0)
else:
cur = stack.pop()
if cur == 0:
stack.append(1)
else:
acc = 0
while cur != 0:
acc += cur
cur = stack.pop()
stack.append(2 * acc)
return sum(stack)
# Example Usage
print(scoreOfParentheses("()")) # Output: 1
print(scoreOfParentheses("(())")) # Output: 2
print(scoreOfParentheses("()()")) # Output: 2
print(scoreOfParentheses("(()(()))")) # Output: 6
(.), calculate the score based on the stack contents:
(), push score 1.This approach ensures that the nested structure’s scores are calculated correctly according to the rules provided.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?