本文主要是介绍leetcode#32. 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.
思路
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 = 0for 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
总结
还需继续努力学习啊,堆栈法的用法还需继续学习…
这篇关于leetcode#32. Longest Valid Parentheses的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!