This is yet another problem dealing with regular bracket sequences.
We should remind you that a bracket sequence is called regular, if by inserting «+» and «1» into it we can get a correct mathematical expression. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.
You are given a string of «(» and «)» characters. You are to find its longest substring that is a regular bracket sequence. You are to find the number of such substrings as well.
The first line of the input file contains a non-empty string, consisting of «(» and «)» characters. Its length does not exceed 106.
Print the length of the longest substring that is a regular bracket sequence, and the number of such substrings. If there are no such substrings, write the only line containing "0 1".
)((())))(()())
6 2
))(
0 1
这一题想到思路就很简单。重点是找),离它最近的没有被匹配的(就是应该跟它匹配,可以记录这一对有多长。然后,()(),对于这种情况,就是两队相邻,第二队加上第一队长度就好了。
#include<cstdio>
#include<iostream>
#include<stack>
using namespace std;
#define MAXN 1000000
int len[MAXN]={0};
int main(){
#ifndef ONLINE_JUDGE
freopen("data","r",stdin);
#endif
string s;
stack<int> st;
int k,maxl=0,n=0;
cin>>s;
for(int i=0; i<s.size(); i++){
if('(' == s[i]){
st.push(i);
}else{
if(!st.empty()){
k = st.top();
st.pop();
len[i] = ( k>0 ? len[k-1] : 0 ) + i+1-k;
if(len[i]>maxl){
maxl = len[i];
n = 1;
}else if(len[i]==maxl)
n++;
}
}
}
if(maxl>0)
cout<< maxl << " " << n << endl;
else
cout<<"0 1"<<endl;
#ifndef ONLINE_JUDGE
fclose(stdin);
#endif
return 0;
}
之前一个错误的思路就是从第一字符到后面的字符,分别找最大长度,顺着数(,用)来抵消,这样在类似()(()(()(这种情况下,每次都要走完,复杂度为n平方,时间过不去。而贪心的方法复杂度仅为n。