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.
动态规划题。难点:理解什么样的串是合法的,知道如何判断串是合法的并知道两个合法串之间是如何被不合法的元素拆分的。要使用one-pass的方式来做,否则会超时。
代码:
class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
st = []
maxlen = 0
last = -1
for i, v in enumerate(s):
if v == '(':
st.append(i)
else:
if not st:
last = i
else:
st.pop()
if st:
maxlen = max(maxlen, i - st[len(st) - 1])
else:
maxlen = max(maxlen, i - last)
return maxlen