数据结构_括号匹配

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <string>
#include <queue>
#include <set>
#include <vector>
#include <algorithm>
#include <stack>
using namespace std;
#define dx 100
#define zl 10
int bz[3][3]={1,0,0,0,1,0,0,0,1};
typedef struct LNode
{
    char *base;
    char *top;
	int stacksize; 
}sqstack;
int Init(sqstack &S) //开辟栈空间    
{   
    S.base=(char *)malloc(dx*sizeof(char));
    if(!S.base)  return -2;
    S.top=S.base;
    S.stacksize=dx;
    return 1;
}
int StackEmpty(sqstack &S) //检测栈是否为空 
{ 
    if(S.top==S.base)  return 1;
    return 0;
}
int Push(sqstack &S,char e) //入栈 
{ 
    if(S.top-S.base>=S.stacksize)
    {
    	S.base=(char *)realloc(S.base,(S.stacksize+zl)*sizeof(char));
    	if(!S.base)  return -2;
    	S.top=S.base+S.stacksize;
    	S.stacksize+=zl;
    }
    *S.top++=e;
    return 1;
}
int  Pop(sqstack &S)//删除栈顶元素 
{ 
    if(S.top==S.base)  return -1;
    --S.top;          return 1;
}
int Top(sqstack &S,char &e)//访问栈顶元素 
{
    if(S.top==S.base)  return -1;
    e=*(S.top-1);      return 1;
}
int is_PP(char s1,char s2)//检查括号是否匹配 
{
	string str1="[({";
	string str2="])}";
	return bz[str1.find(s1)][str2.find(s2)];
}
int is_FX(char c)//检查括号的方向 
{
	if(c=='['||c=='('||c=='{')   return 1;
	else                         return 0;
} 
void is_empty(sqstack &S)//清空栈 
{
	if(S.top!=S.base)
	    S.top=S.base;
}
int main()
{
	char s[105],e;
	sqstack S; Init(S);
	while(cin>>s)
	{
	   int flag=0;
	   for(int i=0;s[i]!='\0';i++)
	   {
		  if(is_FX(s[i]))  Push(S,s[i]);
		  else     
		  {
			if(StackEmpty(S))  
		    {
			   cout<<"0"<<endl;
			   flag=1;
			   break;
			}
			else
			{
			    Top(S,e);
				if(is_PP(e,s[i]))
				{
					Pop(S);
				}
				else
				{
					cout<<"0"<<endl;
			        flag=1;
			        break;
				}
			}
		  }
	   }
	  if(flag==0)
	  {
	    if(StackEmpty(S)) cout<<"1"<<endl;
	    else             cout<<"0"<<endl;
	  }
	  is_empty(S);
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值