https://leetcode-cn.com/problems/longest-valid-parentheses/

# -*- coding:utf-8 -*-

class Solution(object):
    def longestValidParentheses(self, s):
        """
        :type s: str
        :rtype: int
        """
        if not s:
            return 0
        res = 0
        stack = [-1]
        for i in range(len(s)):
            if s[i] == "(":
                stack.append(i)
            else:
                stack.pop()
                if not stack:
                    stack.append(i)
                else:
                    res = max(res, i - stack[-1])
        return res
if __name__ == '__main__':
    s = '))())(()'
    print(Solution().longestValidParentheses(s))

思路:括号匹配首先就是用栈,只要用栈记录连续出栈次数即可。

分类: 算法

0 条评论

发表回复

Avatar placeholder

您的电子邮箱地址不会被公开。 必填项已用 * 标注