Problem C: 括号匹配(栈和队列)
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 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;
}