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

本文介绍了一种高效算法来解决寻找字符串中最长的有效括号子串的问题,并通过动态规划的方法实现了这一算法。
5457

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



