美文网首页
032 Longest Valid Parentheses

032 Longest Valid Parentheses

作者: 英武 | 来源:发表于2019-04-16 13:49 被阅读0次

    Longest Valid Parentheses

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

    Example 1:

    Input: "(()"
    Output: 2
    Explanation: The longest valid parentheses substring is "()"
    

    Example 2:

    Input: ")()())"
    Output: 4
    Explanation: The longest valid parentheses substring is "()()"
    
    class Solution(object):
        def longestValidParentheses(self, s):
            """
            :type s: str
            :rtype: int
            """
            maxlen = 0
            stack = list()
            last = -1
            for i in range(len(s)):
                if s[i] == '(':
                    stack.append(i)
                else:
                    if stack == []:
                        last = i
                    else:
                        stack.pop()
                        if stack == []:
                            maxlen = max(maxlen, i- last)
                        else:
                            maxlen = max(maxlen, i-stack[len(stack)-1])
            return maxlen
    

    一切还可以简化:

    class Solution:
        def longestValidParentheses(self, s: str) -> int:
            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
    

    相关文章

      网友评论

          本文标题:032 Longest Valid Parentheses

          本文链接:https://www.haomeiwen.com/subject/efkbwqtx.html