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
题目大意:给出一个括号字符串,求出它的最大合法字串的长度和最大长度的个数,当最大合法字串长度为0时,输出“0 1”。
思路:利用栈进行维护,每读入一个左括号就将它的下标压栈,每读入一个右括号就将它出栈,因为每一个合法的括号匹配,右括号一定与当前的栈顶左括号匹配,令一个vis[]数组,初始化为0,每次读到右括号就将当前位置和栈顶位置的vis置为1,最后遍历一遍vis数组,找出最大长度连续1的个数以及最大长度的个数即可。注意:最大长度为0时答案需要特判。
参考代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<queue>
#include<stack>
#include<vector>
#include<cmath>
#include<set>
#include<map>
#include<cstdlib>
#include<functional>
#include<climits>
#include<cctype>
#include<iomanip>
using namespace std;
typedef long long ll;
#define INF 0x3f3f3f3f
#define mod 1e9+7
#define clr(a,x) memset(a,x,sizeof(a))
const double eps = 1e-6;
stack <int> Q;
char str[1000010];
int vis[1000010];
void Clear()
{
while(!Q.empty())
Q.pop();
}
int main()
{
while(scanf("%s",str)==1)
{
int len=strlen(str);
int ans=0; //记录最大长度的个数
int maxn=0; //记录最大长度
int cnt=0; //计数器
Clear(); //每次都要将栈清空
clr(vis,0); //将vis初始化为0
for(int i=0;i<len;i++)
{
if(str[i]=='(')
Q.push(i);
if(str[i]==')')
{
if(!Q.empty())
{
vis[i]=1;
vis[Q.top()]=1; //将栈顶位置和当前位置的vis置为1
Q.pop();
}
else
continue;
}
}
vis[len]=0; //强行将lenth位置的元素置为0,防止继续遍历下去
for(int i=0;i<=len;i++)
{
if(vis[i]==1)
{
cnt++; //如果vis为1,就++
}
if(vis[i]==0)
{
if(maxn<cnt) //读到0时,比较最大长度与读到0之前1的个数,如果小于
{
maxn=cnt; //每次都找到最大的长度
ans=1; //说明最大的长度更长,则,最大长度的数量重现置为1
cnt=0; //将cnt清0
}
else if(maxn==cnt) //如果相等,就将最大长度数量加一
{
ans++;
cnt=0;
}
else //如果大于,只将cnt清零
cnt=0;
}
}
if(maxn)
cout<<maxn<<" "<<ans<<endl;
else
puts("0 1"); //当最后遍历完之后发现maxn就每变过,说明就没有找到一个合法匹配的括号,则输出0 1
}
return 0;
}