problem
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.
分析
这是一个优化问题,所以可以使用动态规划来求解,这里我受之前的一个问题的启发把子问题f(i)设为以s[i]为结尾的最长有效括号长度,状态转移方程见代码:
class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
n = len(s)
tmp = [0]
for i in range(1, n):
if s[i] == '(':
tmp.append(0)
else:
if i-1-tmp[i-1] < 0: # 一定要注意下标是否是负数
tmp.append(0)
continue
if s[i-1-tmp[i-1]] == '(':
if i - tmp[i-1] - 2 > -1:
tmp.append(tmp[i-1] + 2 + tmp[i - tmp[i-1] - 2])
else:
tmp.append(tmp[i-1] + 2)
else:
tmp.append(0)
print(tmp)
return max(tmp)
这个算法虽然通过了测试,但是才超过了1%,证明还有优化空间。
利用栈
我们不在对每一个子串都检查合法性,而是在扫描的时候使用栈来检测目前为止的字符串是否合法,在初始时我们将-1压入栈中。
对于每一个’(‘,我们把它的索引压入栈中。
对于每一个’)’,弹出栈顶元素,然后把当前元素的索引减去栈顶元素的索引而得到当前最长的合法长度,如果弹出后栈空了的话,我们把当前元素的索引入栈。代码如下
class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
stack = [-1]
length = 0
for i in range(len(s)):
if s[i] == '(':
stack.append(i)
else:
del stack[-1]
if stack == []:
stack.append(i)
if i - stack[-1] > length:
length = i - stack[-1]
return length
这样代码就超过了97%的提交。证明合适的数据结构可以带来的提升很大,当然对问题深刻的理解才能想到这种解法。