[Leetcode] 32. Longest Valid Parentheses

来源:互联网 发布:mac hexo搭建个人博客 编辑:程序博客网 时间:2024/06/07 06:15

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

For "(()", the longest valid parentheses substring is "()", which has length = 2.

Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.


寻找最长合法括号字串

方法:

建立一个栈,初始时里面只有-1。

碰到 "(" 直接入栈。

碰到 “)” ,先弹栈,如果栈空,则将该括号的index入栈。否则,用该index 减去 栈顶元素(也就是这个括号最远能匹配到的左括号),得到当前最长合法字串的长度。

通过上述规则,记录得到全局的最长即可。

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


原创粉丝点击