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

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

2019-07-28 23:48 155 查看

数据结构实验之栈与队列四:括号匹配
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description

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

Input

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

Output

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

Sample Input

sin(20+10)
{[}]

Sample Output

yes
no

#include<bits/stdc++.h>

using namespace std;

char s[10000];
int main()
{
char st[1000], f;
while(gets(st))
{
int top = 0;
f = 1;
int len = strlen(st);
for(int i = 0; i < len; i++)
{
if(st[i] == ‘(’ || st[i] == ‘[’ || st[i] == ‘{’)
{
s[top++] = st[i];
}
else if(st[i] == ‘)’)
{
if(s[top - 1] != ‘(’)
{
f = 0;
break;
}
else if(s[top - 1] == ‘(’)
{
top–;
}
}
else if(st[i] == ‘]’)
{
if(s[top - 1] != ‘[’)
{
f = 0;
break;
}
else if(s[top - 1] == ‘[’)
{
top–;
}
}
else if(st[i] == ‘}’)
{
if(s[top - 1] != ‘{’)
{
f = 0;
break;
}
else if(s[top - 1] == ‘{’)
{
top–;
}
}
}
if(top != 0) f = 0;///小心右括号都匹配,左多余情况
if(f)
printf(“yes\n”);
else
printf(“no\n”);
}
return 0;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: