输入
第一行输入一个数N(0<N<=100),表示有N组测试数据。后面的N行输入多组输入数据,每组输入数据都是一个字符串S(S的长度小于10000,且S不是空串),测试数据组数少于5组。数据保证S中只含有"[","]","(",")"四种字符
输出
每组输入数据的输出占一行,如果该字符串中所含的括号是配对的,则输出Yes,如果不配对则输出No
#include<stdio.h>
#include<string.h>
char s[11000],c[11000];
int main()
{
int t;
int len;
int i,j,k;
int top;
scanf("%d",&t);
getchar();
while(t--)
{
gets(s);
len=strlen(s);
if(len%2==1)
printf("No\n");
else
{
top=1;
c[0]=s[0];
if(c[0]==']'||c[0]==')')
printf("No\n");
else
{
for(i=1;i<len;i++)
{
c[top]=s[i];
if(c[top-1]=='['&&c[top]==']')
top--;
else if(c[top-1]=='('&&c[top]==')')
top--;
else
top++;
}
if(top==0)
printf("Yes\n");
else
printf("No\n");
}
}
}
return 0;
}
法2指针
#include<stdio.h>
int main()
{
int t;
char c,s[10001],*p;
scanf("%d\n",&t);
while(t--){
*s=getchar();
p=s+1;
while((c=getchar())!='\n'){
if(*(p-1)==c-1||*(p-1)==c-2)
p--;
else
*p++=c;
}
if(p==s)
printf("Yes\n");
else
printf("No\n");
}
}