题解 | #有效括号序列#

有效括号序列

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


char c[10000];
int top=0;
void push(char a){
    printf("%c",a);
    c[top++]=a;
}
bool pop(char a){
    if(a==']'&& '['==c[top-1]){//判断是否匹配
        top--;
        printf("%d ",top);
        return true;
    }
    if(a==')'&& '('==c[top-1]){//判断是否匹配
        top--;
        
        return true;
    }
    if(a=='}'&&'{'==c[top-1]){//判断是否匹配
        top--;
        return true;
    }
    return true;
      
}
bool isValid(char* s ) {
    // write code here
    int i=0;
    //字符串长度为奇数,false
    if(strlen(s)%2==1)
        return false;
    //遍历数组s
    while(s[i]!='\0'){
        if(s[i]=='['||s[i]=='('||s[i]=='{'){
            push(s[i]);

        }else {
            if(pop(s[i])){
                printf("%c",s[i]);   
                }         
            else{
                return false;
            }
        }
        i++;
    }
    if(top==0){
        return true;
        }
    else{
        printf("%d ",666);
        return false;
        }
}

全部评论
耗时比较久的原因是,zai判断是否匹配的时候,总是以为两个字符==,实际匹配 不是 ==
点赞
送花
回复 分享
发布于 05-07 18:10 北京

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务