Problem Description
给你一串字符,不超过50个字符,可能包括括号、数字、字母、标点符号、空格,你的任务是检查这一串字符中的( ) ,[ ],{ }是否匹配。
Input
输入数据有多组,处理到文件结束。
Output
如果匹配就输出“yes”,不匹配输出“no”
Example Input
sin(20+10) {[}]
Example Output
yes no
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<string.h>
#define STACKINITSIZE 100
#define STACKINCREMENT 10
#define OVERFLOW -2
#define ERROR -1
#define OK 1
typedef char SElemType ;
typedef int Statu;
typedef struct node
{
SElemType * base;
SElemType * top;
int stacksize;
} SqStack;
Statu Check(char a[]);
Statu InitList(SqStack &S);
Statu Push(SqStack &S, SElemType e);
Statu Pop(SqStack &S, SElemType &e);
Statu Del_SqStack(SqStack &S);
Statu Compare(SqStack &S, SElemType e);
int main()
{
int f;
char a[60];
while(gets(a))
{
f = Check(a);
if(f == 1)
printf("yes\n");
else
printf("no\n");
}
return 0;
}
Statu Del_SqStack(SqStack &S)
{
S.top = S.base;
return OK;
}
Statu InitStack(SqStack &S)
{
S.base =(SElemType *)malloc(STACKINITSIZE*sizeof(SElemType));
if(!S.base)
exit(OVERFLOW);
S.top = S.base;
S.stacksize = STACKINITSIZE;
return OK;
}
Statu Push(SqStack &S, SElemType e)
{
if(S.top - S.base >= S.stacksize)
{
S.base =(SElemType *)realloc(S.base, (S.stacksize + STACKINCREMENT)*sizeof(SElemType));
if(!S.base)
exit(OVERFLOW);
S.top = S.base + S.stacksize;
S.stacksize += STACKINCREMENT;
}
* S.top++ = e;
return OK;
}
Statu Pop(SqStack &S, SElemType &e)
{
if(S.top == S.base)
e = 'a';
e = * --S.top;
return OK;
}
Statu Compare(SqStack &S, SElemType e)
{
char c;
switch(e)
{
case ')':
Pop(S, c);
if(c == '(')
return OK;
else
return 0;
case ']':Pop(S, c);
if(c == '[')
return OK;
else
return 0;
case '}':Pop(S, c);
if(c == '{')
return OK;
else
return 0;
}
return ERROR;
}
Statu Check(char a[])
{
int i, l, t;
SqStack S;
InitStack(S);
l = strlen(a);
for(i = 0; i < l; i++)
{
if(a[i] == '(' || a[i] == '[' || a[i] == '{')
Push(S, a[i]);
else if(a[i] == ')' || a[i] == ']' || a[i] == '}')
{
t = Compare(S, a[i]);
if(t == 0)
break;
}
}
if(t == 0)
return ERROR;
else if(S.base != S.top)
return ERROR;
else
return OK;
}