题目描述
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.
找出一个只包含”(“和”)”的字符串中最长的有效子字符串的长度。
输入输出示例
解题思路
开辟一个栈,遍历括号字符串序列,如果遇到左括号就压入栈中;如果遇到右括号,弹出左括号,并且最大长度加2
代码实现
def longestValidParentheses(self, s):
maxlen=0
stack=[]
for i in range(len(s)):
if s[i]=='(':
stack.append(s[i])
if s[i]==')' and len(stack)!=0:
stack.pop()
maxlen+=2
return maxlen