题解 | #有效括号序列#
有效括号序列
https://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return bool布尔型
*/
//s为字符串
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
bool isValid(char* s ) {
// write code here
//获取s字符串的长度
int len = strlen(s);
if (len == 0) {
return true;
}
//长度为奇数
else if (len % 2 != 0) {
return false;
}
//用栈的方法,top指针
char Stack[10000];
int top = -1;//栈为空
for (int i = 0; i < len ; i++) {
//将左括号放入栈中
if (s[i] == '{' || s[i] == '(' ||s[i] == '[') {
Stack[ ++ top] = s[i];
continue;
}
//判断栈是否为空
if (top == -1) {
return false;
}
//先不要用==,用!=可以排除多种情况,比较栈顶元素
if (s[i] == ')' && Stack[top] != '(' ||s[i] == '}' && Stack[top] != '{' ||s[i] == ']' && Stack[top] != '[' ) {
return false;
}
top --;//进行下一轮查找
}
//要判断栈顶是否为空,避免输入多个一样的括号
if (top != -1) {
return false;
}
return top == -1;//将元素弹出,栈顶为空
}