括号()
的组合千奇百怪,Drizzle 想知道各种组合的括号可以是否合法
合法要求:每个同类型的左括号必须有与之对应的同类的右括号以正确的顺序闭合
要求:
输入:输入一个括号字符串
输出:输出是否合法,是则True
,否则False
示例:
输入:
(){}[]
输出:
True
范围:
对于 100% 的数据:括号字符串长度 ≤ 100
参考代码
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
// 函数来检查括号字符串是否合法
bool isValid(char * s) {
int n = strlen(s);
if (n % 2 == 1) {
return false;
}
char stack[100];
int top = -1;
for (int i = 0; i < n; i++) {
char c = s[i];
if (c == '(' || c == '{' || c == '[') {
// 如果是左括号,压入栈中
stack[++top] =