题解 | #有效括号序列#
有效括号序列
https://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2?tpId=308&tqId=726&ru=/exam/oj&qru=/ta/algorithm-start/question-ranking&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D308
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return bool布尔型 */ #define Max_Size 10000 typedef struct Stack{ char ch[Max_Size]; int top; }Stack_; bool isValid(char* s ) { // write code here Stack_* S = (Stack_*)malloc(sizeof(Stack_));//创建一个栈 S->top = 0; //将要加入元素位置的下标 int i = 0; while(s[i]){ if(s[i] == '(' || s[i] == '{' || s[i] == '['){ //如果是左括号们就入栈 if(S->top < Max_Size){ S->ch[S->top++] = s[i]; } else{ //栈已满 return false; } } else if(s[i] == ')'){//如果是右括号就出栈并进行比较合法性 if(S->top <= 0 ||S->ch[--(S->top)] != '('){ return false;//不匹配 } } else if(s[i] == '}'){//如果是右括号就出栈并进行比较合法性 if(S->top <= 0 ||S->ch[--(S->top)] != '{'){ return false;//不匹配 } } else if(s[i] == ']'){//如果是右括号就出栈并进行比较合法性 if(S->top <= 0 ||S->ch[--(S->top)] != '['){ return false;//不匹配 } } i++; } //都比较完了如果栈里还剩元素就说明不合法 if(S->top != 0){ return false; } return true; }