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.
题目大意:求最长有效子串长度。valid parentheses判断子串是否有效。这题则要求最长有效的长度。标签式dp。动态规划。
思路:
开始想的是从前往后,用list存截至每个位置时的最长有效字串长度,然后如果下一位是) ,有可能更新maxlen的情况是已这个)开始的最长的有效字串。所以求以该)开始的最长有效长度和上一个位置最大长度比较。取较大者。
用的python写的,超时。有时间试试c++,应该也没问题。
网上看了看别人的思路,自己写了一遍。
从后往前遍历一遍即可。dp[i]数组保存从i开始且首位是s[i]的最长有效字串。然后往左遍历。只有下一位是(时才有可能更新。判断 j=i+dp[i+1]+1的位置的元素是不是)。
然后判断j+1位置是否在界内,是就dp[i] += dp[j+1]。
最后维护一个最大maxlen。在dp中找最大。
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;
}