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"()()"
这题用stack来做,思路是初始化stack用来存放“(”的index,初始化leftmost作为最左边开始的位置,每次遇到“(”就把当前index放入stack,碰到“)”如果当前stack为空,那么就更新leftmost并进入下次循环,当前stack不为空就pop stack,如果这时stack不为空,max长度就是(i-stack[-1]),为空的话,就是i-leftmost。
class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
stack=[]
leftmost=-1
maximal=0
for index,item in enumerate(s):
if item=="(":
stack.append(index)
else:
if not stack:
leftmost=index
else:
stack.pop()
if stack:
maximal=max(maximal,index-stack[-1])
else:
maximal=max(maximal,index-leftmost)
return maximal
本文介绍了一种使用栈来解决最长有效括号子串问题的算法。通过维护一个栈来记录左括号的位置,结合左右括号匹配的逻辑,实现了高效地找到字符串中最大长度的有效括号子串。
1190

被折叠的 条评论
为什么被折叠?



