数据结构实验之栈与队列四:括号匹配
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
给你一串字符,不超过50个字符,可能包括括号、数字、字母、标点符号、空格,你的任务是检查这一串字符中的( ) ,[ ],{ }是否匹配。
Input
输入数据有多组,处理到文件结束。
Output
如果匹配就输出“yes”,不匹配输出“no”
Sample Input
sin(20+10)
{[}]
Sample Output
yes
no
Hint
Source
ma6174
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char a[100],s[100];
int main()
{
while(gets(s)!=NULL)//注意这里不能用scanf因为有空格,只能用scanf,思路没有错,细节出现错误
{
int len=strlen(s);
int f=0,top=0;
for(int i=0; i<len; i++)
{
if(s[i]=='('||s[i]=='{'||s[i]=='[')
a[++top]=s[i];
else
{
if((s[i]==')'&&a[top]=='(')||
(s[i]=='}'&&a[top]=='{')||
(s[i]==']'&&a[top]=='['))
{
top--;
}
else if((s[i]==')'&&a[top]!='(')||
(s[i]=='}'&&a[top]!='{')||
(s[i]==']'&&a[top]!='['))
{
f=1;
break;
}
}
}
if(f==0&&top==0)
{
printf("yes\n");
}
else printf("no\n");
}
return 0;
}

本文介绍了一种使用栈实现括号匹配验证的算法。通过分析输入字符串中的括号类型(圆括号、方括号及花括号),该算法能够判断括号是否正确配对。文章提供了完整的C语言代码实现,并通过示例展示了算法的有效性。
708

被折叠的 条评论
为什么被折叠?



