8-line Python solution, stack, 80ms


  • 1
    K

    To make sure the stack is not empty, first put in a tuple (-1, ')') as it will never be poped out and -1 can be used to calculate result.

    def longestValidParentheses(self, s):
        stack, result = [(-1, ')')], 0
        for i, paren in enumerate(s):
            if paren == ')' and stack[-1][1] == '(':
                stack.pop()
                result = max(result, i - stack[-1][0])
            else:
                stack += (i, paren),
        return result

Log in to reply
 

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