leetcode#32. Longest Valid Parentheses

57 篇文章 0 订阅
14 篇文章 0 订阅

题目

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.

思路

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 onto the stack.

For every
‘(’ encountered, we push its index onto the stack.

For every
‘)’ 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.

这题做的挺不开心的,知道要用堆栈法,可就是做不出来,看了答案原来是这么做,感觉答案就在眼前给错过了..
之前自己的思路是在堆栈中记录左括号,遇到右括号后就弹出,然后计数,这样做的麻烦处在于遇到()(()这种多个左括号,不知道后面会不会匹配的情况时没法计数。
没想到这题堆栈中记录的是左括号的index,当匹配到右括号时就将栈顶弹出,然后用右括号的index减去堆栈顶中存的index,如果栈空了,就将当前右括号的index存入栈中。(栈空只有一种情况,就是当前的右括号没有匹配到左括号,所以将栈底的-1弹出了,将当前index存入栈中其实就是方便后续相减计算长度)
这个算法好处在于通过index的相减计算出了长度,同时还避免了中间计数断开需要从头计数的问题。

代码

class Solution(object):
    def longestValidParentheses(self, s):
        """
        :type s: str
        :rtype: int
        """
        stack = [-1]
        maxlen = 0
        for index, i in enumerate(s):
            if i == '(':
                stack.append(index)
            else:
                pop = stack.pop()
                if stack:
                    maxlen = max(maxlen, index - stack[-1])
                else:
                    stack.append(index)
        return maxlen

总结

还需继续努力学习啊,堆栈法的用法还需继续学习…

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值