forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscore-of-parentheses.py
More file actions
38 lines (33 loc) · 789 Bytes
/
score-of-parentheses.py
File metadata and controls
38 lines (33 loc) · 789 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
# Time: O(n)
# Space: O(1)
class Solution(object):
def scoreOfParentheses(self, S):
"""
:type S: str
:rtype: int
"""
result, depth = 0, 0
for i in xrange(len(S)):
if S[i] == '(':
depth += 1
else:
depth -= 1
if S[i-1] == '(':
result += 2**depth
return result
# Time: O(n)
# Space: O(h)
class Solution2(object):
def scoreOfParentheses(self, S):
"""
:type S: str
:rtype: int
"""
stack = [0]
for c in S:
if c == '(':
stack.append(0)
else:
last = stack.pop()
stack[-1] += max(1, 2*last)
return stack[0]