Problem C: 括号匹配(栈和队列)

Problem C: 括号匹配(栈和队列)

Time Limit: 1 Sec   Memory Limit: 128 MB
Submit: 124   Solved: 30
[ Submit][ Status][ Web Board]

Description

假设一个表达式中只允许包含三种括号:圆括号“(”和“)”,方括号“[”和“]”和花括号“{”和“}”,且这三种括号可按任意的次序嵌套使用如:(…[{… …[]}[]()…]…)。设计一个算法,判断表达式中的括号是否正确配对。输出结果为Yes或者No。

 

顺序栈的定义为

typedef struct
{
    char date[Max];
    int top;
} Spstack;
  
 
需编写的算法为 int solve(char *a,Spstack *st);
 
可使用的函数有:
1、bool Pop(Spstack *&s,char &e);    //出栈
2、bool GetTop(Spstack *s,char &e); //取栈顶元素
3、bool Push(Spstack *&s,char e);     //入栈
4、bool StackEmpty(Spstack *s);        //判断是否为空栈
  
括号匹配正确返回1,否则返回0。其中a为该表达式,st为一个空栈。

Input

{[][]()([])}[]()

Output

Yes

Sample Input

{[()[]][}]

Sample Output

No

HINT

1、注意括号匹配问题


2、只需提交你所编写的算法


#include <stdio.h>
#define Max 105
typedef struct
{
     char date[Max];
     int top;
} Spstack;
void InitStack(Spstack *&s)
{
     s= new Spstack;
     s->top=-1;
}
bool StackEmpty(Spstack *s)
{
     return (s->top==-1);
}
bool Push(Spstack *&s, char e)
{
     if (s->top==Max-1) return false ;
     s->top++;
     s->date[s->top]=e;
     return true ;
}
bool GetTop(Spstack *s, char &e)
{
     if (s->top==-1) return false ;
     e=s->date[s->top];
     return true ;
}
bool Pop(Spstack *&s, char &e)
{
     if (s->top==-1) return false ;
     e=s->date[s->top];
     s->top--;
     return true ;
}
void DestroyStack(Spstack * &s)
{
     delete (s);
} bool solve( char a[],Spstack *&s)
{
     int i=0; char e;
     bool match= true ;
     while (a[i]!= '\0' &&match)
     {
         if (a[i]== '(' ||a[i]== '[' ||a[i]== '{' )
             Push(s,a[i]);
         if (a[i]== ')' ||a[i]== ']' ||a[i]== '}' )
     {
         if (a[i]== ')' &&GetTop(s,e)== true )
        {
            if (e== '(' ) Pop(s,e);
         else match= false ;
        }
         if (a[i]== ']' &&GetTop(s,e)== true )
        {
            if (e== '[' ) Pop(s,e);
         else match= false ;
        }
        if (a[i]== '}' &&GetTop(s,e)== true )
        {
            if (e== '{' ) Pop(s,e);
         else match= false ;
        }
     }
     i++;
}
     if (!StackEmpty(s))
         match= false ;
     return match;
  
}
  
int main()
{
     char a[100];
     bool match;
     Spstack *st;
     InitStack(st);
     gets (a);
     match=solve(a,st);
     DestroyStack(st);
     if (match) printf ( "Yes\n" );
     else printf ( "No\n" );
     return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值