括号配对问题
时间限制:
3000 ms | 内存限制:
65535 KB 难度:
3
- 描述
- 现在,有一行括号序列,请你检查这行括号是否配对。
- 输入
- 第一行输入一个数N(0<N<=100),表示有N组测试数据。后面的N行输入多组输入数据,每组输入数据都是一个字符串S(S的长度小于10000,且S不是空串),测试数据组数少于5组。数据保证S中只含有”[“,”]”,”(“,”)”四种字符
- 输出
- 每组输入数据的输出占一行,如果该字符串中所含的括号是配对的,则输出Yes,如果不配对则输出No
- 样例输入
3 [(]) (]) ([[]()])
- 样例输出
No No Yes
我的思路是用栈来存储,对于只有[]()的元素,分为以下几个步骤:
第一步:存入元素进行判断是否是[或者(:如果是[,判断栈顶元素是否是],是择栈顶元素出栈,否则该元素入栈
第二步:判断栈顶与栈底是否相等,相等择证明完全出栈即完全配对,输出yes,否则即为没有完全配对,输入no!
以下是我的代码,但是WA,有点小郁闷,请各位大神帮忙纠正
#include<stdio.h> #include<malloc.h> #define Max 100 typedef struct Node { int data; struct Node * pNext; }NODE,*PNODE; typedef struct Stack { PNODE Bottom; PNODE Top; }STACK,*PSTACK; void create(PSTACK pS) { pS->Top = (PNODE)malloc(sizeof(NODE)); pS->Bottom = pS->Top; pS->Top->pNext = NULL; } int isEmpty(PSTACK pS) { int n=0; if(pS->Bottom == pS->Top) n = 1; else n = 0; return n; } void push(PSTACK pS,int val) { PNODE pNew = (PNODE)malloc(sizeof(NODE)); if(pNew != NULL) { pNew->data = val; pNew->pNext = pS->Top; pS->Top = pNew; } } void pop(PSTACK pS) { if(pS->Top != pS->Bottom) { PNODE p = pS->Top; pS->Top = p->pNext; free(p); } } void clean(PSTACK pS) { if(pS->Top != pS->Bottom) { PNODE p = pS->Top; PNODE q = NULL; while(p != pS->Bottom) { q = p->pNext; free(p); p = q; } pS->Bottom = pS->Top; } } int main() { PSTACK pS = (PSTACK)malloc(sizeof(STACK)); create(pS); char val; int count,i=0; int r[Max]; scanf("%d",&count); if(count <=0 || count >100) return 0; fflush(stdin); for(i=0;i<count;i++) { while(scanf("%c",&val)) { if(val == '\n') break; if(val == ' ') { continue; } else { if(val == ']') { if(pS->Top->data == '[') pop(pS); else push(pS,val); } else if(val == ')') { if(pS->Top->data == '(') pop(pS); else push(pS,val); } else push(pS,val); } } r[i] = isEmpty(pS); clean(pS); } for(i=0;i<count;i++) { if(r[i] == 0) printf("No\n"); else printf("Yes\n"); } return 0; }