Skip to content

Commit 6eb0714

Browse files
committed
Longest valid parentheses solution
1 parent 1815a66 commit 6eb0714

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

Diff for: 32_longest_valid_parentheses.py

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import pdb
2+
class Solution(object):
3+
# def longestValidParentheses(self, s):
4+
# """
5+
# :type s: str
6+
# :rtype: int
7+
# """
8+
# ls = len(s)
9+
# start = [0] * (ls + 1)
10+
# all = [0] * (ls + 1)
11+
# for i in reversed(range(ls - 1)):
12+
# if s[i] == '(':
13+
# if s[i + 1] == ')':
14+
# start[i] = 2
15+
# if start[i + 1] + i + 1 < ls and s[start[i + 1] + i + 1] == ')':
16+
# start[i] = 2 + start[i + 1]
17+
# if start[start[i] + i] > 0:
18+
# start[i] += start[start[i] + i]
19+
# all[i] = max(start[i], all[i + 1])
20+
# return all[0]
21+
22+
def longestValidParentheses(self, s):
23+
# https://leetcode.com/discuss/87988/my-easy-o-n-java-solution-with-explanation
24+
ls = len(s)
25+
stack = []
26+
data = [0] * ls
27+
for i in range(ls):
28+
curr = s[i]
29+
if curr == '(':
30+
stack.append(i)
31+
else:
32+
if len(stack) > 0:
33+
data[i] = 1
34+
data[stack.pop(-1)] = 1
35+
tep, res = 0, 0
36+
for t in data:
37+
if t == 1:
38+
tep += 1
39+
else:
40+
res = max(tep, res)
41+
tep = 0
42+
return max(tep, res)
43+
44+
if __name__ == '__main__':
45+
s = Solution()
46+
# print s.longestValidParentheses(")(((((()())()()))()(()))(")
47+
print s.longestValidParentheses(')()())')

0 commit comments

Comments
 (0)