原题链接 Problem - 5C - Codeforces
C. Longest Regular Bracket Sequence
2 seconds 256 megabytes
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.
Input
The first line of the input file contains a non-empty string, consisting of «(» and «)» characters. Its length does not exceed 106.
Output
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".
题意
给出一串字符串,只有'('与')',求最长的合法的括号匹配
思路
我们每次将左括号'('压入栈顶,遇见右括号就取出与其匹配,标记为1(在我程序里标记的是与其匹配的位置);如果遇见的右括号没有与之匹配的左括号(栈无元素),那么ans[i]=-1,此处无匹配的。
这样,我们得到了一串数字,要么是-1,要么是1,那么相邻-1之间的元素就是匹配好的,我们取max即可。
以样例为例,“)((())))(()())”那么我们得到的ans数组为{-1,1,1,1,1,1,1,-1,1,1,1,1,1,1},因为两端也需要-1来分隔开,所以手动加入ans[0]=-1,ans[n+1]=-1。
代码
#include<bits/stdc++.h>
using namespace std;
const int N = 1e6+7;
string st;
int len,ans[N],s[N],n,pre,l,num=1,length,answer;
int main()
{
ios::sync_with_stdio(false);
cin>>st;
n=st.length();
st=" "+st;//从1开始,前面补一个空格
for (int i=1;i<=n;i++)
if (st[i]==')')
{
if (len==0) ans[i]=-1;
else
{
pre=s[len--];
ans[pre]=i;//栈顶,与之匹配的位置
ans[i]=pre;
}
}
else
s[++len]=i;//这里栈顶存的是位置
for (int i=1;i<=n;i++)
if (!ans[i]) ans[i]=-1;
ans[0]=ans[n+1]=-1;
for (int r=1,l=0;r<=n+1;r++)
if (ans[r]==-1)
{
length=r-l-1;//区间长度
if (length>answer) answer=length,num=1;//更新
else if (length==answer&&length) num++;//计数
l=r;
}
cout<<answer<<" "<<num;
}
反思
做了那么多字符串括号匹配的问题,我觉得大多数的题目都可以往这样去想,我们将左括号定义为-1,将右括号定义为+1,或者像这样的题目用栈存左括号,未完待续...
感谢
感谢ysy大神的指导