题目就不放了,就是判断一串括号是否能对得上.
也很简单,用个栈就好了.遇到左括号入栈,遇到右括号把栈顶的拿出来比较,对得上就pop,最后判断栈里是否还剩下元素.
我是用c写的,熟悉一下数据结构,用c++应该可以很短.
代码:
#include <stdio.h> #include <stdlib.h> struct stack{ char str[128]; int i; }; char type[4]={'(','[',')',']'}; void ini(struct stack *s){ s->i=0; } void push(struct stack *s,char ch){ s->str[s->i]=ch; s->i++; } char top(struct stack s){ char ch; ch=s.str[s.i-1]; return ch; } void pop(struct stack *s ){ s->i--; } int isempty(struct stack s){ return s.i==0?1:0; } int findpos(char ch){ int pos; if(ch=='(') pos=0; if(ch=='[') pos=1; if(ch==')') pos=2; if(ch==']') pos=3; return pos; } int main() { int n,k,pos; char ch,temp; struct stack s; scanf("%d",&n); getchar(); while(n--){ k=0; ini(&s); while((ch=getchar())!='\n'){ pos=findpos(ch); if(pos==0||pos==1) push(&s,ch); else if(pos==2||pos==3){ pos-=2; temp=top(s); if(temp!=type[pos]){ printf("No\n"); k=1; while((ch=getchar())!='\n'); break; } else pop(&s); } } if(k) continue; if(!isempty(s)) printf("No\n"); else printf("Yes\n"); } return 0; }