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.
class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
s = ')' + s
stack, result = [], 0
for index in range(len(s)):
element = s[index]
if element == ')' and stack and stack[-1][1] == '(':
stack.pop()
result = max(result, index - stack[-1][0])
else:
stack.append((index, s[index]))
return result

本文介绍了一种使用栈来解决寻找字符串中最长有效括号子串长度的方法。通过遍历字符串并利用栈来记录左括号的位置,当遇到右括号时检查栈顶元素是否为匹配的左括号,并更新最长有效子串长度。
238

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



