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.
求最长的合法括号序列~用一个栈记录左括号, 右括号和index,并把stack初始为[(-1, ')')],避免之后处理stack为空的情况~ 如果当前括号是右括号且栈顶是左括号, 则把栈顶弹出并更新maxLen~
class Solution:
# @param s, a string
# @return an integer
def longestValidParentheses(self, s):
if s is None or len(s) == 0: return 0
lenS, stack, maxLen = len(s), [(-1, ')')], 0
for i in xrange(lenS):
if s[i] == ')' and stack[-1][1] == '(':
stack.pop()
maxLen = max(maxLen, i - stack[-1][0])
else:
stack.append((i, s[i]))
return maxLen