zoukankan      html  css  js  c++  java
  • 32. 最长有效括号

    问题描述

    给定一个只包含 '(' 和 ')' 的字符串,找出最长的包含有效括号的子串的长度。

    方法1:栈

    class Solution:
        def longestValidParentheses(self, s: str) -> int:
            # 栈
            lenth = len(s)
            stack = [-1]
            res = 0
            for i in range(lenth):
                if s[i] == '(':
                    stack.append(i)
                else:
                    stack.pop()
                    if not stack:
                        stack.append(i)
                    else:
                        res = max(res, i - stack[-1])     
    
            return res
    

    方法2:贪心一点

    class Solution:
        def longestValidParentheses(self, s: str) -> int:
            #贪心一点,左-->右,右-->左
            lenth = len(s)
            res = 0
            # 左--> 右 
            left = right = 0
            for val in s:
                if val == '(':
                    left += 1
                else:
                    right += 1
                if left == right:
                    res = max(res, 2 * left)
                elif right > left:
                    left = right = 0
    
            # 右-->左
            left = right = 0
            for i in range(lenth - 1, -1, -1):
                if s[i] == ')':
                    right += 1
                else:
                    left += 1
                if left == right:
                    res = max(res, 2 * left)
                elif left > right:
                    left = right = 0
            
            return res
    
  • 相关阅读:
    NPTL 线程同步方式
    mysql事物处理
    DHCP服务器-DNS服务器-Samba服务器
    NTP服务器
    wsgiref 源代码分析
    集群负载均衡LVS
    百万数据查询优化技巧三十则
    Shell 基本运算符
    Shell 数组
    Shell 传递参数
  • 原文地址:https://www.cnblogs.com/libbin/p/longest-Valid-Parentheses.html
Copyright © 2011-2022 走看看