【FZU】Problem 1411 最长配对子串

题目链接:http://acm.fzu.edu.cn/problem.php?pid=1411

题目描述:

Problem Description

给定由(,),[,],{,},<,>构成的一个括号字符串,输出它的一个最长子串,该子串有正确的括号配对。

Input

本题有多组输入数据,每组数据只有一行括号字符串,其长度不大于10000。

Output

对于每组数据,输出该括号字符串的最长配对子串。若答案不唯一,则输出最左边一个;如果答案不存在,则输出“No Solution”。

Sample Input

[()()]][]

Sample Output

[()()]


解题思路:考察栈的知识。

参考代码:


#include<iostream>
#include<string.h>
#include<stack>
using namespace std;
struct node
{
	int pos;
	char ch;
}Node[10010];
int main()
{	
	char s[10010];
	int sign[10010];
	int i;
    int pos;
	char ch;
	
	while(cin>>s)
	{
		stack<node> sta;
		memset(sign,0,sizeof(sign));		
		for(i=0; i<strlen(s); i++)
		{
			if(s[i]=='(' || s[i]=='[' || s[i]=='{' || s[i]=='<')
			{
				Node[i].ch = s[i];
				Node[i].pos = i;
				sta.push(Node[i]);
			}
			else
			{
				if(!sta.empty())
				{
					pos = sta.top().pos;
					ch = sta.top().ch;
					if(ch=='('&&s[i]==')' || ch=='['&&s[i]==']' || ch=='{'&&s[i]=='}' || ch=='<'&&s[i]=='>')
					{
						sign[i] = 1;
						sign[pos] = 1;
						sta.pop();
					}
					else
					{
					    Node[i].ch = s[i];
						Node[i].pos = i;
						sta.push(Node[i]);
					}
				}
			}
		}
		while(!sta.empty())
			sta.pop();

		int begin,end,max=0;
		for(i=0; i<strlen(s); i++)
		{
			if(sign[i]==0) continue;
			else
			{
				int j=i;
				int temp = 0;
				while(sign[j] == 1)
				{
					temp ++;
					j++;
				}
				if(temp > max)
				{
					begin = i;
					end = j-1;
					max = temp;
				}
				i = j-1;
			}	
		}
		if(max != 0)
		{
			for(i=begin; i<=end; i++)
				cout<<s[i];
		}
		else
			cout<<"No Solution";
		cout<<endl;		
	}
	return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值