码迷,mamicode.com
首页 > 其他好文 > 详细

括号匹配

时间:2016-06-05 18:33:06      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define STACK_SIZE 10000
typedef struct STACK{
    char stack[STACK_SIZE];
    int pointer;
}STSTACK;
STSTACK stack;
void push(char ch);
char pop();
int main(int argc, char *argv[])
{
    int num;
    int i;
    char buf[STACK_SIZE]={0};

    scanf("%d",&num);
    getchar();
    for(i = 0;i < num;i++){
        memset(stack.stack, 0x00, STACK_SIZE);
        stack.pointer = -1;

        scanf("%s", buf);
        getchar();

        int len = strlen(buf);
        int j;

        if(buf[0] == ‘]‘ || buf[0] == ‘)‘){
            printf("[0]:No\n");
        }else{
            push(buf[0]);

            for(j = 1;j < len;j++){

                char tmp;
                if(buf[j] == ‘[‘ || buf[j] == ‘(‘){
                    push(buf[j]);
                }else if (buf[j] == ‘]‘) {
                    if(stack.pointer < 0){
                        printf("]:No\n");
                        break;
                    }
                    tmp = pop();
                    if(tmp != ‘[‘){
                        //printf("[]:No\n");
                        push(tmp);
                        break;
                    }

                }else if (buf[j] == ‘)‘) {
                    if(stack.pointer < 0){
                        printf("):No\n");
                        break;
                    }
                    tmp = pop();
                    if(tmp != ‘(‘){
                        //printf("():No\n");
                        push(tmp);
                        break;
                    }
                }

            }

            if(stack.pointer == -1){
                printf("Yes\n");
            }else{
                printf("!-1:No\n");
            }

        }

    }

    return 0;
}

void push(char ch){
    if(stack.pointer >= STACK_SIZE-1){
        printf("top overflow!\n");
        exit(1);
    }
    stack.stack[++stack.pointer] = ch;
}
char pop(){
    return stack.stack[stack.pointer--];
}

括号匹配

标签:

原文地址:http://www.cnblogs.com/guxuanqing/p/5561174.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!