括号匹配这是个很简单的题目,如果只有小括号,就模拟进栈和出栈的过程就行了:
注:输入时'@'作为结束标志
#includeint main(){ freopen("stack.in","r",stdin); freopen("stack.out","w",stdout); int in=0; char s[256]; scanf("%s",&s); int i=0; while(s[i]!='@') { if(s[i]=='(') in++; if(s[i]==')') in--; if(in<0) break; i++; } if(in==0) printf("YES"); else printf("NO"); return 0;}
样例输入1:2*(x+y)/(1-x)@
样例输出1:YES
样例输入2:(25+x)*(a*(a+b+b)@
样例输出2:NO
至于多括号,就需要创建一个栈了:
输入无需@做结尾
#include#include char stack[256];int top=0;void push(char c){ top++;stack[top]=c;}int pop(){ top--;return(stack[top+1]);}int main(){ freopen("check.in","r",stdin); freopen("check.out","w",stdout); char s[256]; gets(s); int lenofs=strlen(s); int i; char c; for(i=0;i<=lenofs-1;i++) { if(s[i]=='(') { push('('); } if(s[i]==')') { push(')'); c=stack[top-1]; if(c=='(') { pop();pop(); } } if(s[i]=='[') { push('['); } if(s[i]==']') { push(']'); c=stack[top-1]; if(c=='[') { pop();pop(); } } if(top<0) break; } if(top==0) printf("OK"); else printf("Wrong"); return 0;}