Sumnous's Blog

LEARN TO DEATH

[Leetcode] Longest Valid Parentheses @Python

Problem

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
    # @param s, a string
    # @return an integer
    def longestValidParentheses(self, s):
        if s == '' or s == '(' or s == ')':
            return 0
        stack = [(-1, ')')]
        maxLen = 0
        for i in xrange(len(s)):
            if s[i] == ')' and stack[-1][1] == '(':
                stack.pop()
                maxLen = max(maxLen, i - stack[-1][0])
            else:
                stack.append((i, s[i]))
        return maxLen
#test
s = Solution()
print s.longestValidParentheses("()(()")
print s.longestValidParentheses('(()()')
print s.longestValidParentheses(')()())')