![]() |
VOOZH | about |
Given a string s, consisting of pairs of balanced parentheses, find the score of the given string based on the given rules:
Examples:
Input: s = โ()()โ
Output: 2
Explanation: The string s is of the form "AB", that makes the total score = (score of A) + (score of B) = 1 + 1 = 2.Input: s = "(()(()))"
Output: 6
Explanation: The string s is of the form "(A(B))" which makes the total score = 2 ร ((score of A) + 2 ร (score of B)) = 2 ร (1 + 2 ร (1)) = 6.
Think of the string as a tree-like structure:
To keep track of scores at each level, we use a stack.
Now, how does the stack help?
The stack keeps track of the score at each level. When we go down '(', we push 0 to start for that level. When we come back through ')', we pop the score of that level:
Then we add this score to the parentโs score (the new top of the stack). At the end, only the root score is left in the stack and thatโs our total score.
6