# leetcode-32-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.

c++ 8ms AC:

class Solution {
public:
int longestValidParentheses(string s) {
int len=s.length();
int dp[len];
int maxl=0;
memset(dp,0,sizeof(dp));
for(int i=len-2;i>=0;i--)
if(s[i]=='(')
{
int j =i+dp[i+1]+1;
if(j<len && s[j]==')')
{
dp[i]=2+dp[i+1];
if(j+1<len)
dp[i]+=dp[j+1];
}
maxl=max(maxl,dp[i]);
}
return maxl;
}
};

python ，自己试了一般的例子，都没问题。只有s特别长的时候超时。

class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
l=len(s)
if l==0 or l==1:
return 0
n=[0]*l
if s[0]=='(' and s[1]==')':n[1]=2
else:n[1]=0
for i in range(2,l):
stack=[]
x=0
m=0
if s[i]==')':
j=i
while(j>=0):
if s[j]==')':
stack.append(1)
if s[j]=='(':
stack.pop()
x=x+1
if len(stack)==0 :
m=m+x
x=0
if s[j-1]=='(':
break
j=j-1
if n[i-1]>=2*m:
n[i]=n[i-1]
else:
n[i]=2*m
else:
n[i]=n[i-1]
return n[l-1]


int longestValidParentheses(string s) {
stack<int> st;
int maxLen=0,accLen=0;

for(int i=0;i<s.length();i++)
if(s[i]=='(')
st.push(i);
else{
if(st.empty())
accLen=0;
else{
int matchedPos=st.top();
st.pop();
int matchedLen=i-matchedPos+1;
if(st.empty()){
accLen+=matchedLen;
matchedLen=accLen;
}
else
matchedLen=i-st.top();

maxLen=max(maxLen,matchedLen);
}
}

return maxLen;
}
• 本文已收录于以下专栏：

举报原因： 您举报文章：leetcode-32-Longest Valid Parentheses 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)