zoukankan      html  css  js  c++  java
  • 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/

  • 相关阅读:
    Xcode 环境下的汇编与 C/C++/ObjC (上)
    OpenGL ES的从地上爬起来,第1部分:
    Accessorizer的使用说明!
    我常用的iphone开发学习网站
    ruby+seleniumwebdriver一步一步完成自动化测试(2)—–一个测试用例
    Selenium Grid深入学习
    Seleniumwebdriver系列教程(14)————为firefox设置代理
    Seleniumwebdriver系列教程(15)————万能的截图
    Selenium Grid
    RSPEC入门学习
  • 原文地址:https://www.cnblogs.com/bernieloveslife/p/9762655.html
Copyright © 2011-2022 走看看