在C语言中,我们可以使用栈数据结构来实现括号匹配检查
#include<stdio.h>
#include <stdlib.h>
#include<string.h>
typedef struct Stack {
char *data;
int top;
int size;
} Stack;
Stack *createStack(int size) {
Stack *stack = (Stack *)malloc(sizeof(Stack));
stack->data = (char *)malloc(size * sizeof(char));
stack->top = -1;
stack->size = size;
return stack;
}
void push(Stack *stack, char value) {
if (stack->top == stack->size - 1) {
printf("Stack is full\n");
return;
}
stack->data[++stack->top] = value;
}
char pop(Stack *stack) {
if (stack->top == -1) {
printf("Stack is empty\n");
return '\0';
}
return stack->data[stack->top--];
}
int isEmpty(Stack *stack) {
return stack->top == -1;
}
int isMatchingPair(char opening, char closing) {
if (opening == '(' && closing == ')') return 1;
if (opening == '{' && closing == '}') return 1;
if (opening == '[' && closing == ']') return 1;
return 0;
}
int areBracketsBalanced(char *expression) {
int length = strlen(expression);
Stack *stack = createStack(length);
for (int i = 0; i< length; i++) {
if (expression[i] == '(' || expression[i] == '{' || expression[i] == '[') {
push(stack, expression[i]);
} else if (expression[i] == ')' || expression[i] == '}' || expression[i] == ']') {
if (isEmpty(stack)) {
return 0;
} else {
char openingBracket = pop(stack);
if (!isMatchingPair(openingBracket, expression[i])) {
return 0;
}
}
}
}
return isEmpty(stack);
}
int main() {
char expression[] = "({[]})";
if (areBracketsBalanced(expression)) {
printf("The brackets are balanced\n");
} else {
printf("The brackets are not balanced\n");
}
return 0;
}
这个程序首先定义了一个栈结构,然后实现了创建栈、入栈、出栈等基本操作。接下来,我们定义了一个isMatchingPair
函数,用于判断两个括号是否匹配。areBracketsBalanced
函数遍历输入的字符串,遇到开括号就入栈,遇到闭括号就出栈并检查是否匹配。最后,如果栈为空,说明括号匹配成功,否则失败。
在main
函数中,我们测试了一个包含圆括号、花括号和方括号的字符串,如果括号匹配,输出"The brackets are balanced",否则输出"The brackets are not balanced"。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。