题解 | 有效括号序列
有效括号序列
https://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return bool布尔型 */ #include <stdbool.h> #include <string.h> bool isValid(char* s ) { // write code here char stack[10000]; int top = -1; for (int i = 0; i < strlen(s); i++) { if (s[i] == '(' || s[i] == '[' || s[i] == '{') { top++; stack[top] = s[i]; } if (s[i] == ')') { if (stack[top] == '(') { top--; } else { return false; } } if (s[i] == ']') { if (stack[top] == '[') { top--; } else { return false; } } if (s[i] == '}') { if (stack[top] == '{') { top--; } else { return false; } } } if(top==-1){ return true; } return false; }
本题用数组来代表栈,遍历字符串,当是左括号字符时入栈,当是右括号字符时判断栈顶是否为相应的左括号,不是则返回false;最后遍历完后判断栈是否为空(判断是否有多出来的括号),空则表示全部匹配完毕,return true,否则return true。