题解 | #有效括号序列#
有效括号序列
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[strlen(s)];
int top = -1; //top指向stack辅助栈的-1位置
for(int i = 0;i < strlen(s);i++){
if (strlen(s)==0){
return false;//如果为空字符串,返回false
}
if (s[i] == '(') {
stack[++top] = ')';
}
if (s[i] == '[') {
stack[++top] = ']';
}
if (s[i] == '{') {
stack[++top] = '}';
}
if ( s[i] == ')' || s[i] == ']' || s[i] == '}'){
if(top==-1){
return false;//如果读到了右括号,但是站里面没有对应括号了,直接返回false
}
if (stack[top]!=s[i]) {
return false;
}
if (stack[top]==s[i]){
top--;
}
}
}
if(top == -1){
return true;
}else {
return false;
}
}
查看22道真题和解析
