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

数据结构实验之栈与队列四:括号匹配
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;
}

猜你喜欢

转载自blog.csdn.net/bhliuhan/article/details/81181854