-
Notifications
You must be signed in to change notification settings - Fork 57
/
Solution.py
66 lines (41 loc) · 1.01 KB
/
Solution.py
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"""
Given a balanced parentheses string S, compute the score of the string based on the following rule:
() has score 1
AB has score A + B, where A and B are balanced parentheses strings.
(A) has score 2 * A, where A is a balanced parentheses string.
Example 1:
Input: "()"
Output: 1
Example 2:
Input: "(())"
Output: 2
Example 3:
Input: "()()"
Output: 2
Example 4:
Input: "(()(()))"
Output: 6
Note:
S is a balanced parentheses string, containing only ( and ).
2 <= S.length <= 50
"""
class Solution:
def scoreOfParentheses(self, S: str) -> int:
stk = []
for c in S:
if c == '(':
stk.append(c)
continue
val = 0
while stk and stk[-1] != '(':
val += stk[-1]
stk.pop()
if stk and stk[-1] == '(':
stk.pop()
if val == 0:
stk.append(1)
else:
stk.append(val * 2)
return sum(stk)