51nod 1478 括号序列的最长合法子段(栈-括号匹配寻找最长合法子串长度及其个数)

题目来源:  CodeForces
基准时间限制:1 秒 空间限制:131072 KB 分值: 40  难度:4级算法题
 收藏
 关注

这里有另一个关于处理合法的括号序列的问题。

如果插入“+”和“1”到一个括号序列,我们能得到一个正确的数学表达式,我们就认为这个括号序列是合法的。例如,序列"(())()", "()"和"(()(()))"是合法的,但是")(", "(()"和"(()))("是不合法的。

这里有一个只包含“(”和“)”的字符串,你需要去找到最长的合法括号子段,同时你要找到拥有最长长度的子段串的个数。


Input
第一行是一个只包含“(”和“)”的非空的字符串。它的长度不超过 1000000。
Output
输出合格的括号序列的最长子串的长度和最长子串的个数。如果没有这样的子串,只需要输出一行“0  1”。
Input示例
)((())))(()())
Output示例
6 2


题解:看错题目了,以为是找所有合法子串个数。想了半天,发现是找最长的。 那么就很简单了,用一个栈维护,将没办法形成匹配的括号及其位置放进一个栈里面,那么最后栈内每两个括号之间就有一个合法串,然后从前往后扫一遍,记录下最长合法串长度及其个数就好了。


代码如下:


#include <cstdio>
#include <cstring>
#include <algorithm>
#include <stack>
using namespace std;
const int maxn = 1e6+10;
struct node
{
	int id;
	char s;
}temp; 
stack<node> tac;
char str[maxn];
int main()
{
	while(scanf("%s",str)!=EOF)
	{
		int len=strlen(str);
		int Max=0,cnt=1;
		while(!tac.empty())
			tac.pop();
		for(int i=0;i<len;++i)
		{
			if(str[i]=='(')
			{
				temp.id=i;
				temp.s='(';	
				tac.push(temp);
			}
			else
			{
				if(tac.empty())
				{
					temp.id=i;
					temp.s=')';
					tac.push(temp);
				}
				else
				{
					temp=tac.top();
					if(temp.s==')')
					{
						temp.id=i;
						tac.push(temp);
					}
					else
						tac.pop();
				}
			}
		}
		if(tac.empty())
			Max=len;
		else
		{
			temp=tac.top();
			int L=len-temp.id-1;
			Max=L;
			while(!tac.empty())
			{
				temp=tac.top();
				tac.pop();
				if(tac.empty()){
					if(temp.id>Max)
					{
						Max=temp.id;
						cnt=1;
					}
					else if(temp.id==Max)
						cnt++;
				}
				else
				{
					node step=tac.top();
					L=temp.id-step.id-1;
					if(L==Max)
						cnt++;
					else if(L>Max){
						cnt=1;
						Max=L;
					}
				}
			}
		}
		if(Max==0)
			cnt=1;
		printf("%d %d\n",Max,cnt);
	}
	return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值