TOP101题解 | BM44#有效括号序列#
有效括号序列
https://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * @author Senky * @date 2023.08.24 * @par url https://www.nowcoder.com/creation/manager/content/584337070?type=column&status=-1 * @brief * (:ASCII 码值为 40 * ):ASCII 码值为 41 * {:ASCII 码值为 123 * }:ASCII 码值为 125 * [:ASCII 码值为 91 * ]:ASCII 码值为 93 * @param s string字符串 * @return bool布尔型 */ #include <stdlib.h> #include <string.h> #include <stdio.h> bool isValid(char* s ) { // write code here int len = strlen(s); if (*s == '\0' || len % 2 == 1) { //奇数个符号肯定不匹配 return false; } char stack[len]; // 栈 int top = -1; // 栈顶索引 for (int i = 0; i < len; i++) { if (s[i] == '(' || s[i] == '[' || s[i] == '{') { // 遇到左括号,入栈 stack[++top] = s[i]; } else if (top >= 0 && ((s[i] == ')' && stack[top] == '(') || (s[i] == ']' && stack[top] == '[') || (s[i] == '}' && stack[top] == '{'))) { // 遇到右括号且与栈顶元素匹配,出栈 top--; } else { // 遇到右括号但与栈顶元素不匹配,返回 false return false; } } //最后栈一定为空,栈顶指针为-1 return (top == -1); }#TOP101#
TOP101-BM系列 文章被收录于专栏
系列的题解