自己突然想到的方法.适合我这样的14级新手0.0 可以做出来
如果'('的数量和')'一样,'['和']'数量一样就可能对,如果错误就是在'('后面为']'或者'['后面为')';
#include <stdio.h> int main() { int t,i,j,flag,sum1,sum2,sum3,sum4; char a[10002],c; scanf("%d",&t); getchar(); while(t--) { i=0; sum1=sum2=sum3=sum4=0; while((c=getchar())!='\n') { a[i++]=c; if(c=='(') sum1++; if(c==')') sum2++; if(c=='[') sum3++; if(c==']') sum4++; } flag=1; for(j=0;j<i;j++) if(a[j]=='('&&a[j+1]==']'||a[j]=='['&&a[j+1]==')') flag=0; if(sum1==sum2&&sum3==sum4&&flag==1) printf("Yes\n"); else printf("No\n"); } return 0; }
栈的方法
#include <stdio.h> #include <string.h> #include <stack> using namespace std; int main() { int t,i; char str[10010]; stack<char>s; scanf("%d",&t); while(t--) { memset(str,0,sizeof(str)); scanf("%s",str); s.push('1');//为了防止str[0]=']'||')'不然会导致s.top()访问到不该访问的地方 for(i=0;str[i]!='\0';i++) { if(str[i]=='['||str[i]=='(') s.push(str[i]); else if(str[i]==']'&&s.top()=='[') s.pop(); else if(str[i]==')'&&s.top()=='(') s.pop(); else break; } if(str[i]=='\0') printf("Yes\n"); else printf("No\n"); while(s.top()!='1') s.pop(); } return 0; }