算法思路:
-
初始化一个栈,命名为s
-
依次遍历待匹配的字符串
-
如果当前字符为左括号(即'(', '[', '{'中的任意一个),则将其入栈
-
如果当前字符为右括号(即')', ']', '}'中的任意一个),则需要进行匹配检测
代码:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MaxSize 100 // 栈的最大容量
// 定义栈结构体
typedef struct {
char data[MaxSize];
int top; // 栈顶指针
} Stack;
// 初始化栈
void init(Stack *s) {
s->top = -1; // 置空栈
}
// 判断栈是否为空
bool is_empty(Stack *s) {
return s->top == -1;
}
// 判断栈是否已满
bool is_full(Stack *s) {
return s->top == MaxSize - 1;
}
// 元素入栈
void push(Stack *s, char c) {
if (is_full(s)) {
printf("栈已满!\n");
exit(EXIT_FAILURE);
}
s->top++;
s->data[s->top] = c;
}
// 元素出栈
char pop(Stack *s) {
if (is_empty(s)) {
printf("栈为空!\n");
exit(EXIT_FAILURE);
}
char c = s->data[s->top];
s->top--;
return c;
}
// 判断括号序列是否匹配
bool is_matched(char *str) {
Stack s;
init(&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 (is_empty(&s)) { // 栈为空,无法匹配
return false;
} else if ((str[i] == ')' && pop(&s) != '(') ||
(str[i] == ']' && pop(&s) != '[') ||
(str[i] == '}' && pop(&s) != '{')) { // 栈顶元素与右括号不匹配
return false;
}
}
i++;
}
return is_empty(&s); // 栈为空,则括号匹配成功,否则匹配失败
}
// 测试代码
int main() {
char str[MaxSize];
printf("请输入括号序列:");
scanf("%s", str);
if (is_matched(str)) {
printf("括号匹配成功!\n");
} else {
printf("括号匹配失败!\n");
}
return 0;
}
效果图:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)