括号配对问题
时间限制:3000 ms | 内存限制:65535 KB
难度:3
- 描述
- 现在,有一行括号序列,请你检查这行括号是否配对。
- 输入
- 第一行输入一个数N(0<N<=100),表示有N组测试数据。后面的N行输入多组输入数据,每组输入数据都是一个字符串S(S的长度小于10000,且S不是空串),测试数据组数少于5组。数据保证S中只含有"[","]","(",")"四种字符
- 输出
- 每组输入数据的输出占一行,如果该字符串中所含的括号是配对的,则输出Yes,如果不配对则输出No
- 样例输入
-
3 [(]) (]) ([[]()])
- 样例输出
-
No No Yes
代码:#include<stdio.h> #include<string.h> char m[10010],n[10010]; int top; void push(char x){top++; m[top]=x; } void pop(char *x){*x=m[top]; top--; } int main(){ int T,i,flot;char temp; scanf("%d",&T); while(T--){i=top=0;flot=1; memset(m,0,sizeof(m)); scanf("%s",n); while(n[i]){ if(n[i]=='['||n[i]=='(')push(n[i]); else{pop(&temp); if(temp=='('&&n[i]==']')flot=0; if(temp=='['&&n[i]==')')flot=0; } /* printf("%d m[%d]=%c ",i,top,m[top]);*/i++; }if(top!=0)flot=0; if(flot)printf("Yes "); else printf("No "); } return 0; }
时间为0;01.#include<stdio.h>02.#include<string.h>03.charm[10010],n[10010];04.inttop;05.voidpush(charx){top++;06.m[top]=x;07.}08.voidpop(){09.top--;10.}11.intmain(){12.intT,i;13.scanf("%d",&T);14.while(T--){i=top=0;15.memset(m,0,sizeof(m));16.scanf("%s",n);17.while(n[i]){18.if(n[i]==']'&&m[top]=='[')pop();19.elseif(n[i]==')'&&m[top]=='(')pop();20.elsepush(n[i]);21./* printf("%d m[%d]=%c ",i,top,m[top]);*/i++;22.}23.if(top==0)printf("Yes ");24.elseprintf("No ");25.}26.return0;27.}两种代码时间对比: