基于栈的实现,左括号进栈,右括号匹配出栈。注意,当栈空时有两种情况,匹配成功或是原匹配串的右括号数目大于左括号数目。因此,加了标志。
代码如下:
#include<cstdio>
#include<cstring>
#define max 10010
char str[max];
char stack[max];
int top;
int main()
{
int n,tag;
scanf("%d",&n);getchar();
for(int i=0;i<n;i++)
{
gets(str);
top=tag=0;
for(int j=0;str[j]!='\0';j++)
{
if(str[j]=='['||str[j]=='(')
stack[top++]=str[j];
else
if(str[j]==']'&&top&&stack[top-1]=='[')
top--;
else
if(str[j]==')'&&top&&stack[top-1]=='(')
top--;
else
if(str[j]!=' ')
{tag=1;break;}
}
if(tag||top) printf("No\n");
else
printf("Yes\n");
}
return 0;
}