• 32.Longest Valid Parenttheses


    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 "()()"

    Solution1:(TLE) Brute Force

    class Solution(object):
        def longestValidParentheses(self, s):
            """
            :type s: str
            :rtype: int
            """
            def judge(string):
                count = 0
                for i in string:
                    if i=='(':
                        count += 1
                    else:
                        count -= 1
                        if count<0:
                            return False
                if count>0:
                    return False
                return True
    
            def solve(i):
                left = 0
                while left<i+1:
                    if judge(s[left:i+1]):
                        return i-left+1
                    left += 1
                return 0
    
            if len(s)==0 or len(s)==1:
                return 0
            n = len(s)
            dp = [0 for i in range(n)]
            for i in range(1,n):
                dp[i] = max(dp[i-1],solve(i))
            return dp[-1]
    

    189 / 230 test cases passed.

    Solution2:

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

    Algorithm

    Instead of finding every possible string and checking its validity, we can make use of stack while scanning the given string to check if the string scanned so far is valid, and also the length of the longest valid string. In order to do so, we start by pushing −1-1−1 onto the stack.

    For every ‘(’ ext{‘(’}‘(’ encountered, we push its index onto the stack.

    For every ‘)’ ext{‘)’}‘)’ encountered, we pop the topmost element and subtract the current element's index from the top element of the stack, which gives the length of the currently encountered valid string of parentheses. If while popping the element, the stack becomes empty, we push the current element's index onto the stack. In this way, we keep on calculating the lengths of the valid substrings, and return the length of the longest valid string at the end.
    Reference:https://leetcode.com/problems/longest-valid-parentheses/solution/

  • 相关阅读:
    小知识!
    命令级的python静态资源服务。
    自定义滚动条样式-transition无效
    css:a:visited限制
    react16 渲染流程
    virtual-dom
    用video标签流式加载
    golang 代码笔记
    position:fixed not work?
    go/node/python 多进程与多核cpu
  • 原文地址:https://www.cnblogs.com/bernieloveslife/p/9762655.html
Copyright © 2020-2023  润新知