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/

  • 相关阅读:
    MySQL在大数据Limit使用
    debian非正常关机进不了图形界面的解决方法
    debian 系统备份
    数据库对内存的存储与读取
    QT: QByteArray储存二进制数据(包括结构体,自定义QT对象)
    Mysql数据库备份和按条件导出表数据
    QTableWidget控件总结
    Mysql数据库导入命令Source详解
    Mysql数据库导出压缩并保存到指定位置备份脚本
    Mysql导出表结构及表数据 mysqldump用法
  • 原文地址:https://www.cnblogs.com/bernieloveslife/p/9762655.html
Copyright © 2011-2022 走看看