Codeforces 5C - Longest Regular Bracket Sequence(字符串/括号匹配/栈)

原题链接 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大神的指导

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值