-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path06_score_of_parentheses.py
More file actions
42 lines (32 loc) · 992 Bytes
/
06_score_of_parentheses.py
File metadata and controls
42 lines (32 loc) · 992 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Solution:
def scoreOfParentheses_1(self, s: str) -> int:
stack = []
for char in s:
if char == "(":
stack.append(char)
else: # char == ")"
if stack[-1] == "(":
stack.pop()
stack.append(1)
else:
val = 0
while stack[-1] != "(":
val += stack.pop()
stack.pop()
stack.append(2 * val)
return sum(stack)
def scoreOfParentheses(self, s: str) -> int:
stack = [0]
for char in s:
if char == '(':
stack.append(0)
else:
v = stack.pop()
stack[-1] += max(2 * v, 1)
return stack.pop()
if __name__ == "__main__":
obj = Solution()
s1 = "()"
print(obj.scoreOfParentheses(s1))
s2 = "()(())"
print(obj.scoreOfParentheses(s2))