-
Notifications
You must be signed in to change notification settings - Fork 43
/
score-of-parentheses.py
82 lines (78 loc) · 1.88 KB
/
score-of-parentheses.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# V0
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/84956643
class Solution(object):
def scoreOfParentheses(self, S):
"""
:type S: str
:rtype: int
"""
stack = []
score = 0
for c in S:
if c == '(':
stack.append("(")
else:
tc = stack[-1]
if tc == '(':
stack.pop()
stack.append(1)
else:
num = 0
while stack[-1] != '(':
num += stack.pop()
stack.pop()
stack.append(num * 2)
return sum(stack)
# V1'
# https://blog.csdn.net/fuxuemingzhu/article/details/84956643
class Solution(object):
def scoreOfParentheses(self, S):
"""
:type S: str
:rtype: int
"""
stack = [0]
score = 0
for c in S:
if c == '(':
stack.append(0)
else:
v = stack.pop()
stack[-1] += max(v * 2, 1)
return sum(stack)
# V2
# 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 range(len(S)):
if S[i] == '(':
depth += 1
else:
depth -= 1
if S[i-1] == '(':
result += 2**depth
return result
# V2'
# 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]