Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<string.h>
- #include<stdlib.h>
- #define OK 0
- #define ERROR -1
- #define MAXSIZE 100
- //定义栈
- struct Stack{
- int top; //栈顶下标
- char S[MAXSIZE];//字符数组
- };
- typedef struct Stack stack;
- //栈初始化
- void init(stack *s)
- {
- s->top=0;
- }
- //判断栈是否为空
- int empty(stack *s)
- {
- if(s->top==0) return 1;
- return 0;
- }
- //判断栈是否为满
- int full(stack *s)
- {
- if(s->top==MAXSIZE) return 1;
- return 0;
- }
- //压栈
- int push(stack *s,char c)
- {
- if(full(s)) //上溢
- return ERROR;
- s->S[s->top]=c;
- s->top++;
- return OK;
- }
- //出栈
- int pop(stack *s)
- {
- if(empty(s)) //下溢
- return ERROR;
- char c;
- c=s->S[s->top--];
- return OK;
- }
- //括号匹配
- int match(stack *s,char st[])
- {
- int i,len;
- char c;
- init(s);
- len=strlen(st);
- for(i=0;i<len;i++)
- {
- c=st[i];
- if(c=='('||c=='['||c=='{') //如果是左括号则进栈
- push(s,c);
- else if(c==')') //如果是右括号则出栈匹配
- {
- if(empty(s)) return ERROR;//下溢
- else if(s->S[s->top]=='(') pop(s); //匹配则出栈
- else return ERROR;
- }
- else if(c==']')
- {
- if(empty(s)) return ERROR;//下溢
- else if(s->S[s->top]=='[') pop(s); //匹配则出栈
- else return ERROR;
- }
- else if(c=='}')
- {
- if(empty(s)) return ERROR;//下溢
- else if(s->S[s->top]=='{') pop(s); //匹配则出栈
- else return ERROR;
- }
- else return ERROR; //如果不是()[]{}这六种符号则返回-1.
- }
- if(empty(s)) return OK; //全部匹配,返回0
- return ERROR;
- }
- int main()
- {
- int n;
- char st[1000];
- stack *s;
- s=(stack*)malloc(sizeof(stack));
- init(s); //初始化栈
- scanf("%d",&n); //输入要检测的字符串组数
- while(n--)
- {
- scanf("%s",st); //输入要检测的字符串
- if (match(s,st)) printf("correct\n");
- else printf("error\n");
- }
- free(s);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement