Friday, September 19, 2014

Leetcode: Longest Valid Parentheses @Python

class Solution:
    # @param s, a string
    # @return an integer
    def longestValidParentheses(self, s):
        n=len(s)
        stack=[(')',-1)]
        maxlen=0
        for i in range(n):
            if s[i]==')' and stack[-1][0]=='(':
                stack.pop()
                maxlen=max(maxlen,i-stack[-1][1])
            else:
                stack.append((s[i],i))
        return maxlen

No comments :

Post a Comment