输入:第一行输入一个数N(0<N<=100),表示有N组测试数据。后面的N行输入多组输入数据,每组输入数据都是一个字符串S(S的长度小于10000,且S不是空串),测试数据组数少于5组。数据保证S中只含有"[","]","(",")"四种字符。
输出:每组输入数据的输出占一行,如果该字符串中所含的括号是配对的,则输出Yes,如果不配对则输出No
样例输入:
3 [(]) (]) ([[]()])样例输出:
No No Yes 这是南阳理工学院ACM练习题,我的程序如下:在练习这道题时,我学会了①栈的知识和用法;②二维数组动态空间的开辟和释放方法;③最重要的是学会了这种思维方式,mark一下。
#include <stdio.h> #include <stdlib.h> #include <string.h> #define TRUE 1 #define FALSE 0 #define StackSize 10000 typedef struct{ char data[StackSize]; int top; }SqStack; int num1 = 0,num2 = 0; void InitStack(SqStack *s); int StackEmpty(SqStack *s); int StackFull(SqStack *s); int Push(SqStack *s,char x); char Pop(SqStack *s); int StackTop(SqStack *s,char *x); void Bracket(SqStack *s, char *a); int main(void) { int N = 0; int i = 0,j = 0,k = 0; int *length; char **s; SqStack S; scanf("%d",&N); //开辟二位数组动态内存空间,N行10000列 s = (char **)malloc(sizeof(char *)*N); for(i = 0;i < N;i++) s[i] = (char *)malloc(sizeof(char)*10000); for(i = 0;i < N;i++) { if(‘\n‘ == getchar()) { scanf("%s",s[i]); } } for(i = 0;i < N;i++) { Bracket(&S, s[i]); if(num1 == 0 && num2 == 0) { printf("YES\n"); } else printf("NO\n"); num1 = num2 = 0; } system("pause"); for(i = 0;i < N;i++) free(s[i]); free(s); return 0; } void Bracket(SqStack *s, char *a) { int i,j,length = strlen(a); InitStack(s); for(i = 0;i < length;i++) { switch(a[i]) { case ‘[‘:Push(s,a[i]);num1++;break; case ‘(‘:Push(s,a[i]);num2++;break; case ‘]‘: if(‘[‘ == Pop(s) || FALSE == Pop(s)) { num1--; } break; case ‘)‘: if(‘(‘ == Pop(s) || FALSE == Pop(s)) { num2--; } break; default:break; } } } void InitStack(SqStack *s) { s->top = -1; //初始化的顺序栈为空 } int StackEmpty(SqStack *s) { if(s->top == -1) return TRUE; else return FALSE; } int StackFull(SqStack *s) { if(s->top == StackSize-1) return TRUE; else return FALSE; } int Push(SqStack *s,char x) { if(StackFull(s)) { //printf("StackFull~\n"); return FALSE; } else { s->top++; s->data[s->top] = x; return TRUE; } } char Pop(SqStack *s) { if(StackEmpty(s)) { //printf("StackEmpty~\n"); return FALSE; } else { return s->data[s->top--]; } } int StackTop(SqStack *s,char *x) { if(StackEmpty(s)) { //printf("StackEmpty~\n"); return FALSE; } else { *x = s->data[s->top]; return TRUE; } }
时间: 2024-11-09 09:43:30