C语言判断一个字符串是否为有效的括号序列
时间: 2023-11-21 09:56:27 浏览: 70
以下是C语言判断一个字符串是否为有效的括号序列的代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
// 定义栈结构体
typedef struct {
char data[MAX_SIZE];
int top;
} Stack;
// 初始化栈
void initStack(Stack *s) {
s->top = -1;
}
// 判断栈是否为空
int isEmpty(Stack *s) {
return s->top == -1;
}
// 判断栈是否已满
int isFull(Stack *s) {
return s->top == MAX_SIZE - 1;
}
// 入栈
void push(Stack *s, char c) {
if (isFull(s)) {
printf("Stack is full.\n");
exit(0);
}
s->data[++s->top] = c;
}
// 出栈
char pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty.\n");
exit(0);
}
return s->data[s->top--];
}
// 判断是否为左括号
int isLeft(char c) {
return c == '(' || c == '[' || c == '{';
}
// 判断是否为右括号
int isRight(char c) {
return c == ')' || c == ']' || c == '}';
}
// 判断左右括号是否匹配
int isMatch(char left, char right) {
return (left == '(' && right == ')') || (left == '[' && right == ']') || (left == '{' && right == '}');
}
// 判断字符串是否为有效的括号序列
int isValid(char *s) {
Stack stack;
initStack(&stack);
int len = strlen(s);
for (int i = 0; i < len; i++) {
if (isLeft(s[i])) {
push(&stack, s[i]);
} else if (isRight(s[i])) {
if (isEmpty(&stack) || !isMatch(pop(&stack), s[i])) {
return 0;
}
}
}
return isEmpty(&stack);
}
int main() {
char s[MAX_SIZE];
printf("请输入一个括号序列:");
scanf("%s", s);
if (isValid(s)) {
printf("该括号序列是有效的。\n");
} else {
printf("该括号序列是无效的。\n");
}
return 0;
}
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)