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/

  • 相关阅读:
    Asp.net MVC3 Razor语法小记
    asp.net4的webform使用路由
    判断数据库中要创建的存储过程、函数等是否已经存在
    visual studio 解决方案版本互转
    sql语句创建表的时候加表注释和列注释
    Jquery在指定元素内查找元素(相对定位)
    .net便利的小方法
    sqlserver2008秘钥
    jquery星级评定效果(原创)
    清除GridView自带样式
  • 原文地址:https://www.cnblogs.com/bernieloveslife/p/9762655.html
Copyright © 2011-2022 走看看