简单的括号匹配

Sample Input

([(][()]]()

([)]

Sample Output

[()]

 
  
题意 :  求括号序列的最长合法序列 , 没有合法的不用输出;
用栈实现匹配,匹配的标为1 ,同时记下在序列中的下标,用结构体存好了;
#include<cstdio>
#include<cstring>
#include<map>
#include<vector>
#include<cmath>
#include<cstdlib>
#include<stack>
#include<queue>
#include <iomanip>
#include<iostream>
#include<algorithm>
using namespace std ;


struct node
{
    char c ;
	int num ;	
}e[101000];  
 char s[101000] ; 
 int  match[101000]; 
 int top ;
 
 int main()
 {   int t = 0 ;
 	while(~scanf("%s",s)) 
 	{
 		int len = strlen(s);
		for( int i = 0 ; i < len ; i++)
		{
			  e[i].c=s[i] ;
			  e[i].num=i;
				memset(match,0,sizeof(match)) ; 
		 stack<node>a ; 
		for(int i = 0 ; i < len ; i++)
		{
			if(!a.empty())
			{
				int w=a.top().num ;
				char ch=a.top().c ;  
				if( ch=='(' && e[i].c == ')' || ch=='[' && e[i].c == ']')
				{
					   match[i]=1 ;
					   match[w]=1; 
					   a.pop();
					   
				}
				else   a.push(e[i]) ;
						else
			     a.push(e[i]) ;
		}
		
		int  flag=0,wan=0 , cout=0, MAX=0;
		for(int i = 0 ; i< len ; i++)
		{
			 if(match[i]==1)
			     cout++;
			 else
			 {
			 	  if(cout>MAX)
			 	  {
			 	  	  MAX=cout ;
			 	  	  wan=i-1 ;
			 	  }
			 	  cout=0;
		     }
		     if(cout) flag=1;
		}  
		if(!flag)  puts("");
		else  
		{
			if(cout) //最后一个没有处理,最后一段1
			{
				if(cout>MAX)
				{
					MAX=cout;
					wan=len-1;
				}
			}
			for(int i = wan-MAX+1 ; i <= wan ;i++)
			      printf("%c",s[i]);
				puts("");
		}
		puts("");
 	}
 	return 0;
 } 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值