有趣的括号c语言代码
时间: 2023-09-03 12:13:07 浏览: 93
以下是一个使用 C 语言编写的有趣的括号代码,它可以判断一组括号序列是否合法(即左右括号匹配):
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#define MAX_SIZE 100
bool isValid(char* s) {
char stack[MAX_SIZE]; // 定义栈
int top = -1; // 栈顶指针
int len = strlen(s); // 字符串长度
for (int i = 0; i < len; i++) {
switch (s[i]) {
case '(':
case '[':
case '{':
stack[++top] = s[i];
break;
case ')':
if (top == -1 || stack[top--] != '(') {
return false;
}
break;
case ']':
if (top == -1 || stack[top--] != '[') {
return false;
}
break;
case '}':
if (top == -1 || stack[top--] != '{') {
return false;
}
break;
}
}
return top == -1;
}
// 测试代码
int main() {
printf("%d\n", isValid("()")); // true
printf("%d\n", isValid("()[]{}")); // true
printf("%d\n", isValid("(]")); // false
printf("%d\n", isValid("([)]")); // false
printf("%d\n", isValid("{[]}")); // true
return 0;
}
```
这个代码使用了数组来实现栈的功能。具体实现思路与前面介绍的 Python 和 C++ 版本的代码类似。
这个代码的时间复杂度是 $O(n)$,其中 $n$ 是字符串的长度。