括号配对问题

来源:互联网 发布:涉密软件开发资质 编辑:程序博客网 时间:2024/06/06 00:00

描述
现在,有一行括号序列,请你检查这行括号是否配对。
输入
第一行输入一个数N(0 < N< =100),表示有N组测试数据。后面的N行输入多组输入数据,每组输入数据都是一个字符串S(S的长度小于10000,且S不是空串),测试数据组数少于5组。数据保证S中只含有”[“,”]”,”(“,”)”四种字符
输出
每组输入数据的输出占一行,如果该字符串中所含的括号是配对的,则输出Yes,如果不配对则输出No
样例输入
3
[(])
(])
([])
样例输出
No
No
Yes

#include<cstdio>#include<cmath>#include<cstring>#include<algorithm>using namespace std;int P(char *p){    int x,y;    char *ptemp;    ptemp=p;    while(*ptemp!='\0')    {        x=0;        y=0;        if(*ptemp=='(')        {            x++;        }        else if(*ptemp=='[')        {            y++;        }        else         {            return -1;        }        //判断首字符         if(x)//如果首字符是'('         {            while((*(++ptemp)!='\0')&&(x!=0))//这里的(x!=0)是判断串位的关键            {                if(*ptemp=='(')                {                    x++;                }                if(*ptemp=='[')                {                    y++;                }                if(*ptemp==')')                {                    x--;                    if(x<0)                    {                        return -1;                    }                }                if(*ptemp==']')                  {                      y--;                      if(y<0)                    {                      return -1;                    }                }            }            if(y)            {                return -1;            }        }        if(y)//如果首字符是'['         {            while((*(++ptemp)!='\0')&&y!=0)            {                if(*ptemp=='(')                {                    x++;                }                 if(*ptemp=='[')                {                    y++;                }                if(*ptemp==')')                {                    x--;                    if(x<0)                    {                        return -1;                    }                }                if(*ptemp==']')                {                    y--;                    if(y<0)                    {                        return -1;                    }                }               }            if(x)             {                return -1;            }        }    }    return 0; }int main(){    int t;    int x=0;    int y=0;    scanf("%d",&t);    while(t--)    {        char s[10010];        scanf("%s",&s);        int leng=strlen(s);        int j=0;        while(s[j]!='\0')        {            switch(s[j])            {                case'(':x++;break;                case')':x--;break;                case'[':y++;break;                case']':y--;break;            }            j++;        }        if(x==0&&y==0)        {            int ans=P(s);            if(ans==0)            {                printf("Yes\n");            }            else             {                printf("No\n");             }         }        else        {            printf("No\n");        }        x=0;        y=0;    }    return 0;}
原创粉丝点击