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,string is "()(())",length=6.
即给定一个只有左右小括号的字符串,求最长的括号匹配字串长。
方法一 栈法
这是解决括号匹配最经典做法。解法:维护一个栈,栈底值为上次匹配失败的位置首先初始放一个-1入栈代表上次匹配失败的地方为-1依次扫描字符若为'(',将位置放入栈中若为')',若栈中元素大于1个,则代表有'('可匹配,更新最优值,否则更新栈底
int longestValidParentheses(string s){
int maxlen=0,len;
if(s.size()<2)return maxlen;
stack<int> ss;
ss.push(-1);//栈底为匹配失败的位置
int i=0;
char t;
while(i<s.size()){
char c=s[i];
if(c=='(')ss.push(i);
else{
if(ss.size()>1){ss.pop();len=i-ss.top();if(maxlen<len)maxlen=len;}//有(可匹配,更新最优值
else{ss.pop();ss.push(i);}//更新栈底
}
i++;
}
return maxlen;
}
方法二 动态规划
DP是解决最值问题的有效方法。引入动态数组dp[],且dp[i]表示从下标i开始到字符串结束的最长括号长度,则
1 s[i]=='(':
d[i]=d[i+1]+2 when j=i+d[i+1]+1处为右括号,则s[i ... j]为有效括号匹配,在求得了s[i ... j]的有效匹配长度之后,若j + 1没有越界,则dp[i]的值还要加上从j + 1开始的最长有效匹 配,即dp[j + 1]
d[i]=0 when i+d[i+1]+1处为左括号
2 s[i]==')':
d[i]=0
int longestValidParentheses(string s){
int *dp=(int*)malloc(sizeof(int)*s.size());
for(int i=0;i<s.size();i++)dp[i]=0;
int maxlen=0;
for(int i=s.size()-2;i>=0;i--){
if(s[i]=='('){
int end=i+dp[i+1]+1;
if(end<s.size()&&s[end]==')'){dp[i]=dp[i+1]+2;if(end+1<s.size())dp[i]+=dp[end+1];}
}
if(maxlen<dp[i])maxlen=dp[i];
}
return maxlen;
}