Skip to content

Commit 4de6f82

Browse files
Leetcode 856
1 parent 5f6e9a4 commit 4de6f82

1 file changed

Lines changed: 58 additions & 0 deletions

File tree

Leetcode/Leetcode_856.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
class Solution:
2+
def scoreOfParentheses(self, s: str) -> int:
3+
"""
4+
LeetCode 856 - Score of Parentheses
5+
6+
Approach (Stack):
7+
- Use a stack to store the score at each level of nesting.
8+
- Initialize the stack with 0, representing the score of the
9+
outermost level.
10+
- Traverse each character in the string:
11+
1. If the character is '(':
12+
- Start a new nested level by pushing 0 onto the stack.
13+
2. If the character is ')':
14+
- Pop the score of the current level.
15+
- If the popped score is 0, it represents "()", whose score is 1.
16+
- Otherwise, it represents "(A)", whose score is 2 * A.
17+
- Add the calculated score to the previous level.
18+
19+
Why stack = [0]?
20+
- The initial 0 acts as the base level.
21+
- Every completed parenthesis contributes its score to its parent level.
22+
- Without this base level, the first completed pair would have
23+
nowhere to store its score.
24+
25+
Example:
26+
Input: s = "(()(()))"
27+
28+
Stack Evolution:
29+
Start -> [0]
30+
( -> [0, 0]
31+
( -> [0, 0, 0]
32+
) -> [0, 1]
33+
( -> [0, 1, 0]
34+
( -> [0, 1, 0, 0]
35+
) -> [0, 1, 1]
36+
) -> [0, 3]
37+
) -> [6]
38+
39+
Output: 6
40+
41+
Time Complexity: O(n)
42+
- Each character is processed exactly once.
43+
44+
Space Complexity: O(n)
45+
- In the worst case, the stack stores one score for each level
46+
of nested parentheses.
47+
"""
48+
49+
stack = [0]
50+
51+
for ch in s:
52+
if ch == "(":
53+
stack.append(0)
54+
else:
55+
current_score = stack.pop()
56+
stack[-1] += max(2 * current_score, 1)
57+
58+
return stack[0]

0 commit comments

Comments
 (0)