一.问题描述
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
二.代码编写
这道题虽然是hard,但是很简单。首先要清楚怎样的括号子串是合法的,第一个要满足的条件是左括号个数一定要小于右括号个数。不过这样只适合判断子串是否为合法的。我想的方法是通过出入栈的方式,将匹配的括号弹出栈,那么最后剩下括号及其在原串中的位置,通过位置之间的最大差来得到最大合法括号子串。代码如下:
class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
stack_list = [] # 新建一个括号栈list[即用list实现栈]
len_s = len(s)
for i in range(len_s):
ss = s[i]
if ss == '(':
stack_list.append([i,ss]) # 左括号入栈
else:
if stack_list != [] and stack_list[-1][1]=='(':
stack_list.pop() # 右括号,若栈顶是左括号则弹出栈
else:
stack_list.append([i,ss]) #右括号,若栈顶为右括号或栈已空,则右括号入栈
stack_list.append([len_s,0])
maxr = 0
before = -1
for sta in stack_list: # 找到最大括号间隔
maxr = max(maxr,sta[0]-before-1)
before = sta[0]
return maxr
很明显是线性时间复杂度。