leetcode32_Longest Valid Parentheses

一.问题描述

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

For "(()", the longest valid parentheses substring is "()", which has length = 2.

Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4

即给定一个只含有左右括号的字符串,输出其最长有效左右括号的长度。


二.代码编写

    这道题虽然是hard,但是很简单。首先要清楚怎样的括号子串是合法的,第一个要满足的条件是左括号个数一定要小于右括号个数。不过这样只适合判断子串是否为合法的。我想的方法是通过出入栈的方式,将匹配的括号弹出栈,那么最后剩下括号及其在原串中的位置,通过位置之间的最大差来得到最大合法括号子串。代码如下:

class Solution(object):
    def longestValidParentheses(self, s):
        """
        :type s: str
        :rtype: int
        """
        stack_list = []   # 新建一个括号栈list[即用list实现栈]
        len_s = len(s)
        for i in range(len_s):
            ss = s[i]
            if ss == '(':
                stack_list.append([i,ss])  # 左括号入栈
            else:
                if stack_list != [] and stack_list[-1][1]=='(':
                    stack_list.pop()   # 右括号,若栈顶是左括号则弹出栈
                else:
                    stack_list.append([i,ss]) #右括号,若栈顶为右括号或栈已空,则右括号入栈
        stack_list.append([len_s,0]) 
        maxr = 0
        before = -1
        for sta in stack_list:  # 找到最大括号间隔
            maxr = max(maxr,sta[0]-before-1)
            before = sta[0]
        return maxr
很明显是线性时间复杂度。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值