您的位置:首页 > 理论基础 > 数据结构算法

数据结构实验之栈四:括号匹配

2016-10-05 15:42 253 查看

数据结构实验之栈四:括号匹配

Time Limit: 1000MSMemory Limit: 65536KB
[align=center]SubmitStatistic[/align]

Problem Description

给你一串字符,不超过50个字符,可能包括括号、数字、字母、标点符号、空格,你的任务是检查这一串字符中的( ) ,[ ],{ }是否匹配。

Input

输入数据有多组,处理到文件结束。

Output

如果匹配就输出“yes”,不匹配输出“no”

Example Input

sin(20+10)

{[}]


Example Output

yes

no

 

#include<stdio.h>
#include<malloc.h>
#include<string.h>
#define maxsize 52
#define plus 10
char s[51];
int m=0;
struct node
{
char *base;
char *top;
int stacksize;
};
int init(node &L)
{
L.base=(char *)malloc(maxsize*sizeof(char));
if(!L.base)return -1;
L.top=L.base;
L.stacksize=maxsize;
return 0;
}
int push(node &L,char e)
{
if(L.top-L.base>=L.stacksize)
{
L.base=(char *)malloc((L.stacksize+plus)*sizeof(char));
if(!L.base)return -1;
L.top=L.base+L.stacksize;
L.stacksize+=plus;
}
*L.top=e;
L.top++;
return 0;
}
void creat(node &L,char a[])
{
int i;
int len;
len=strlen(a);
m=0;
for(i=0;i<len;i++)
{
if(a[i]=='('||a[i]=='['||a[i]=='{')
{
m++;
push(L,a[i]);
}
else if(a[i]==')')
{
if(m==0||*(L.top-1)!='(')
{
printf("no\n");
return;
}
else
{
L.top--;
m--;
}
}
else if(a[i]==']')
{
if(m==0||*(L.top-1)!='[')
{
printf("no\n");
return ;
}
else
{
L.top--;
m--;
}
}
else if(a[i]=='}')
{
if(m==0||*(L.top-1)!='{')
{
printf("no\n");
return;
}
else
{
L.top--;
m--;
}
}
}
if(m==0)printf("yes\n");
else printf("no\n");
return ;
}
int main()
{
node L;
while(gets(s)!=NULL)
{
init(L);
creat(L,s);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: