题解 | #有效括号序列#

有效括号序列

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;
    }
}

全部评论

相关推荐

09-14 17:23
门头沟学院
故事和酒66:所以说副业很重要,程序员干到40岁,再怎么也赚300万了,吃吃利息也够活下去
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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