32. Longest Valid Parentheses

约 1 分钟

LeetCode 每日一题:Longest Valid Parentheses

LeetCode 原题

Given a string containing just the characters '(' and ')', return the length of the longest valid (well-formed) parentheses substring.

Constraints:

  • 0 <= s.length <= 3 * 104
  • s[i] is '(', or ')'.

思路

完全没思路,冥思苦想40分钟

python
class Solution:
    def longestValidParentheses(self, s: str) -> int:
        stack = [-1]
        ans = 0
        for i, c in enumerate(s):
            if c == '(':
                stack.append(i)
            else:
                stack.pop()
                if not stack:
                    stack.append(i)
                else:
                    ans = max(ans, i-stack[-1])
        return ans
标签栈

返回文章列表