`

括号配对问题--一道ACM在线测试题

 
阅读更多

今天在南阳理工学院的在线ACM测试上做了一道题,简直弱爆了。。。请看原题:

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

我的解:

#include <stdio.h>
#include <string.h>

int Peidui(char *p)
{
 int xx,yy;
 char *ptmp;
 ptmp=p;
 while( *ptmp !='\0')
 {
  xx=yy=0;
  if( *ptmp == '(' )
  {
   xx=1;
  }
  else if( *ptmp == '[')
  {
   yy=1;
  }
  else return -1;
  if(xx)
  {
   while((*(++ptmp) !='\0') && (xx != 0))
   {
    if(*ptmp == '(')
     xx++;
    if(*ptmp == '[')
     yy++;
    if(*ptmp == ')')
     {
      xx--;
      if(xx<0)
       return -1;
     }
     
    if(*ptmp == ']')
     {
      yy--;
      if(yy<0)
       return -1;
     }
   }
   if(yy)
   {
    return -1;
   }
  }
  if(yy)
  {
   while((*(++ptmp) !='\0')&&(yy != 0))
   {
    if(*ptmp == '(')
     xx++;
    if(*ptmp == '[')
     yy++;
    if(*ptmp == ')')
     {
      xx--;
      if(xx<0)
       return -1;
     }
    if(*ptmp == ']')
     {
      yy--;
      if(yy<0)
       return -1;
     }
   }
   if(xx)
   {
    return -1;
   }
  }
 }
 return 0;
 
}

int main()
{
 int testNum,res,i=0,j=0;
 int x=0,y=0,len;
 char testData[10010];
 scanf("%d",&testNum);
 if((testNum<=0) || (testNum>100))
  return 0;
 for(i=0;i<testNum;i++)
 {
  scanf("%s",testData); 
  len=strlen(testData);
  if((len>=10000) && (len==0))
  {
   i--;
   continue;
  }
  j=0;
  while(testData[j] !='\0')
  {
   switch(testData[j])
   {
    case '(':x++;break;
    case ')':x--;break;
    case '[':y++;break;
    case ']':y--;break;
    //default:return 0;
   }
   j++;
  }
  if(x==0 && y==0)
  {
   res=Peidui(testData);
   if(res==0)
    printf("Yes\n");
   else
    printf("No\n");
  }
  else 
   printf("No\n");
  x=y=0;
 }
 return 0;
}


大家如果有兴趣,可以去这个网站打发一下时间。也挺有趣的。http://acm.nyist.net/JudgeOnline/problemset.php

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics