Python Solution


  • 1
    Y
    def longestValidParentheses(self, s):
        stack, longest, index = [0], 0, 0
        
        for index in xrange(0, len(s)):
            if s[index] == ")" and len(stack) != 1:
                length, last = stack.pop(), stack.pop()
                total_length = last + length + 2
                stack.append(total_length)
                longest = max(longest, total_length)
            elif s[index] == "(":
                stack.append(0)
            else:
                stack = [0]
        
        return longest

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.