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/

  • 相关阅读:
    OpenLayers测量距离和面积
    BeanUtils接口和类
    深入理解Spring--动手实现一个简单的SpringIOC容器
    Spring:源码解读Spring IOC原理
    Spring AOP的底层实现原理
    ClassLoader工作机制
    Cglib及其基本使用
    InvocationHandler和Proxy(Class)的动态代理机制详解
    解密Redis的持久化和主从复制机制
    Redis之父九条编程忠告
  • 原文地址:https://www.cnblogs.com/bernieloveslife/p/9762655.html
Copyright © 2011-2022 走看看