nyoj_2:括号配对问题

来源:互联网 发布:手机版组态软件 编辑:程序博客网 时间:2024/04/28 03:56

模拟栈的操作,很基础的一道题

题目链接

#include<stdio.h>#include<stdlib.h>#include<string.h>char a[11000],b[11000];//b即stack;int main(){    int n;    scanf("%d",&n);    getchar();//屏蔽回车;    while(n--)    {        int len,top=1,i;        gets(a);        b[top++]=a[0];        len=strlen(a);                if((a[0]!='[')&&(a[0]!='(')||(len%2==1)) printf("No\n");//若第一个元素为")"或"]"输入个数为奇数,No;        else        {            for(i=1;    i<len;    i++)            {                if(a[i]=='('||a[i]=='[') b[top++]=a[i];//满足进栈条件,进栈;                else                {                    if(a[i]==']'&&b[top-1]=='[') top--;//满足出栈条件;                    else if(a[i]==')'&&b[top-1]=='(') top--;                    else b[top++]=a[i];                }            }            if(top==1) printf("Yes\n");//如果最后top回到原位( 都配对 );            else printf("No\n");        }    }    return 0;}


0 0