题解 | #有效括号序列#

有效括号序列

https://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param s string字符串 
 * @return bool布尔型
 */
 #include <stdbool.h>
#define MAX  10000
char panduan(char c){  //测姻缘,看看你的另一半是谁
    if(c == ']'){
        return '[';
    }
    if(c == ')'){
        return '(';
    }
    if(c == '}'){
        return '{';
    }
    return 0;
}

bool isValid(char* s ) {

    char a[MAX]; //辅助数组(做栈用)
    int top = 0; //辅助数组的指针(栈顶指针)
    int i = 0; //遍历s的指针
    while (s[i] != 0) { //遍历s,记得while中最后一行的i++
        a[top] = s[i]; //入栈
        top++; //栈顶指针指向栈顶的下一个位置
        if(top>=2 && panduan(a[top-1]) == a[top-2]){ //如果有两个以上的元素且最上边俩是一对
            top -= 2; //最上边俩出栈
        }
        i++;
    }
    return top!=0?false:true; //三目表达式,如果全部入栈完后,辅助数组(栈)为空,则为有效
}

#23届找工作求助阵地#
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务