编辑代码

#include <stdio.h>
#include <stdbool.h>

#define MAX_SIZE 100

typedef struct {
    char data[MAX_SIZE];
    int top;
} Stack;

void initStack(Stack *s) {
    s->top = -1;
}

bool isEmpty(Stack *s) {
    return s->top == -1;
}

bool isFull(Stack *s) {
    return s->top == MAX_SIZE - 1;
}

void push(Stack *s, char c) {
    if (isFull(s)) {
        printf("Stack is full.\n");
        return;
    }
    s->data[++(s->top)] = c;
}

char pop(Stack *s) {
    if (isEmpty(s)) {
        printf("Stack is empty.\n");
        return '\0';
    }
    return s->data[(s->top)--];
}

char top(Stack *s) {
    if (isEmpty(s)) {
        printf("Stack is empty.\n");
        return '\0';
    }
    return s->data[s->top];
}

int checkBrackets(char* str) {
    Stack s;
    initStack(&s);
    int i = 0;
    while (str[i] != '\0') {
        if (str[i] == '(' || str[i] == '{' || str[i] == '[') {
            push(&s, str[i]);
        } else if (str[i] == ')' || str[i] == '}' || str[i] == ']') {
            if (!isEmpty(&s) && ((str[i] == ')' && top(&s) == '(') ||
                                 (str[i] == '}' && top(&s) == '{') ||
                                 (str[i] == ']' && top(&s) == '['))) {
                pop(&s);
            } else {
                return 0; // 括号不匹配
            }
        }
        i++;
    }
    return isEmpty(&s); // 如果栈为空则括号匹配成功,否则括号不匹配
}

int main() {
    char str[MAX_SIZE];
    printf("请输入括号序列:");
    scanf("%s", str);

    if (checkBrackets(str)) {
        printf("括号匹配成功\n");
    } else {
        printf("括号不匹配\n");
    }

    return 0;
}