/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return bool布尔型 */ #include <stdbool.h> #include <stdlib.h> #include <string.h> #define MAX_STACK_SIZE 10000 typedef struct stack { char st[MAX_STACK_SIZE]; int index; } stack; void push(stack* a, char s) { if (a->index == MAX_STACK_SIZE - 1) { exit(1); } else { a->st[++a->index] = s; } } char pop(stack* a) { if (a->index == -1) { exit(1); } else return a->st[a->index--]; } bool isValid(char* s ) { stack a = { .index = -1 }; int length = strlen(s); for (int i = 0; i < length; i++) { if (s[i] == '[' || s[i] == '{' || s[i] == '(') { push(&a, s[i]); } else if (s[i] == ']' && (a.index == -1 || a.st[a.index] != '[')) { return false; } else if (s[i] == '}' && (a.index == -1 || a.st[a.index] != '{')) { return false; } else if (s[i] == ')' && (a.index == -1 || a.st[a.index] != '(')) { return false; } else if (s[i] == ']' || s[i] == '}' || s[i] == ')') { pop(&a); } } // 如果栈为空,则所有开括号都找到了匹配的闭括号 return a.index == -1; }