括号配对问题

试写一个判别表达式中开、闭括号是否配对出现的算法

#include <stdio.h>  
#include <stdlib.h>  
#include <stdbool.h>  
#include <string.h>  
  
// 栈结构定义  
typedef struct {  
    char *array;  
    int top;  
    int capacity;  
} Stack;  
  
// 初始化栈  
void initStack(Stack *s, int capacity) {  
    s->array = (char *)malloc(capacity * sizeof(char));  
    if (!s->array) {  
        fprintf(stderr, "Memory allocation failed\n");  
        exit(EXIT_FAILURE);  
    }  
    s->top = -1;  
    s->capacity = capacity;  
}  
  
// 检查栈是否为空  
bool isEmpty(Stack *s) {  
    return s->top == -1;  
}  
  
// 入栈操作  
void push(Stack *s, char item) {  
    if (s->top + 1 >= s->capacity) {  
        fprintf(stderr, "Stack overflow\n");  
        exit(EXIT_FAILURE);  
    }  
    s->array[++s->top] = item;  
}  
  
// 出栈操作  
char pop(Stack *s) {  
    if (isEmpty(s)) {  
        fprintf(stderr, "Stack underflow\n");  
        exit(EXIT_FAILURE);  
    }  
    return s->array[s->top--];  
}  
  
// 检查括号是否配对的函数  
bool areParenthesesBalanced(const char *expression) {  
    Stack s;  
    int capacity = 100; // 假设输入不会太长  
    initStack(&s, capacity);  
  
    for (int i = 0; expression[i] != '\0'; i++) {  
        if (expression[i] == '(' || expression[i] == '[' || expression[i] == '{') {  
            push(&s, expression[i]);  
        } else if (expression[i] == ')' || expression[i] == ']' || expression[i] == '}') {  
            if (isEmpty(&s)) {  
                // 没有匹配的左括号  
                free(s.array);  
                return false;  
            }  
            char topChar = pop(&s);  
            if ((expression[i] == ')' && topChar != '(') ||  
                (expression[i] == ']' && topChar != '[') ||  
                (expression[i] == '}' && topChar != '{')) {  
                // 括号不匹配  
                free(s.array);  
                return false;  
            }  
        }  
    }  
  
    // 检查栈是否为空,如果为空说明所有括号都匹配成功  
    bool result = isEmpty(&s);  
    free(s.array);  
    return result;  
}  
  
int main() {  
    char expression[101]; // 假设用户输入的最大长度为100个字符  
    printf("Enter an expression to check for balanced parentheses: ");  
    if (fgets(expression, sizeof(expression), stdin) == NULL) {  
        fprintf(stderr, "Failed to read input\n");  
        return EXIT_FAILURE;  
    }  
    // 去除fgets可能读取的换行符  
    expression[strcspn(expression, "\n")] = 0;  
  
    if (areParenthesesBalanced(expression)) {  
        printf("The expression is balanced.\n");  
    } else {  
        printf("The expression is not balanced.\n");  
    }  
  
    return 0;  
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值