/
Longest_Valid_Parentheses.py
56 lines (46 loc) · 1.38 KB
/
Longest_Valid_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
class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
stack = [] # list as a stack
ret = 0 # return value
last = -1
for i in range(len(s)):
if s[i] == '(':
stack.append(i)
else:
if not stack:
last = i
else:
stack.pop()
if stack==[]:
ret = max(ret,i-last)
else: # there are multiple remaining left brackets
ret = max(ret,i-stack[-1])
#print("i is {} and ret temp is {},ret is {}".format(0,ret_temp,ret))
return ret
def stringToString(input):
return input[1:-1].decode('string_escape')
def intToString(input):
if input is None:
input = 0
return str(input)
def main():
import sys
def readlines():
for line in sys.stdin:
yield line.strip('\n')
lines = readlines()
while True:
try:
line = lines.next()
s = stringToString(line)
ret = Solution().longestValidParentheses(s)
out = intToString(ret)
print out
except StopIteration:
break
if __name__ == '__main__':
main()