基於棧的實現,左括號進棧,右括號匹配出棧。注意,當棧空時有兩種情況,匹配成功或是原匹配串的右括號數目大於左括號數目。因此,加了標誌。
代碼如下:
#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;
}