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

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

2016-11-17 08:43 225 查看

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

Time Limit: 1000MS Memory Limit: 65536KB
[align=center]Submit Statistic Discuss[/align]

Problem Description

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

Input

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

Output

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

Example Input

sin(20+10){[}]


Example Output

yesno

每种情况都要考虑到

#include<iostream>
#include<stack>
#include<cstring>
#include<cstdio>
using namespace std;

int main()
{
char ch[1000],str[1000];
while(gets(str))
{
int p=0;
for(int i=0;i<strlen(str);i++)
{
if(str[i]=='{'||str[i]=='}'||str[i]=='('||str[i]==')'||str[i]=='['||str[i]==']')
{
ch[p++]=str[i];
}
}//puts(ch);
int a=0,b=0,c=0,l=1;
for(int i=0;i<p;++i)
{
if(!l) break;
switch(ch[i])
{
case '(':a++;break;
case ')':
if(a)
a--;
else l=0;
break;
case '{':b++;break;
case '}':
if(b)
b--;
else
l=0;
break;
case '[':c++;break;
case ']':
if(c)
c--;
else
l=0;
break;
}
}
int k=0;//printf("-%d-\n",l);
if((a==0&&b==0&&c==0)&&l)
{
for(int i=0;i<strlen(ch)-1;i++)
{
if(ch[i]=='{'&&ch[i+1]==']'||ch[i]=='{'&&ch[i+1]==')'||ch[i]=='['&&ch[i+1]==')'||ch[i]=='['&&ch[i+1]=='}'||ch[i]=='('&&ch[i+1]==']'||ch[i]=='('&&ch[i+1]=='}')
{
k=1;
printf("no\n");
}

}
if(!k)
printf("yes\n");
}
else
printf("no\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: