LeetCode20--有效的括号

思想:左括号入栈,右括号出栈顶与左括号匹配。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。

typedef char STDataType;
typedef struct stack{
    STDataType*a;
    int top;
    int capacity;
}ST;
//初始化栈
void STInit(ST*pst){
    assert(pst);
    pst->top=pst->capacity=0;
    pst->a=NULL;
}

//入栈
void STPush(ST*pst,STDataType x){
    assert(pst);
    if(pst->top==pst->capacity){ //空间不够进行增容
        int newcapacity=pst->capacity==0?4:pst->capacity*2;
        STDataType*tmp=(STDataType*)realloc(pst->a,newcapacity*sizeof(STDataType));
        if(tmp==NULL){
        perror("realloc fail");
        return;
        }
        pst->a=tmp;
        pst->capacity=newcapacity;
    }
    pst->a[pst->top]=x;
    pst->top++;
}
//出栈
void STPop(ST*pst){
    assert(pst);
    assert(pst->top>0);
    pst->top--;
}
//取栈顶元素
STDataType STTop(ST*pst){
    assert(pst);
    assert(pst->top>0);
    return pst->a[pst->top-1];
}
//判空
bool STEmpty(ST*pst){
    assert(pst);
    return pst->top==0;
}
bool isValid(char*s){
    ST st;
    STInit(&st);
    while(*s){
        //左括号入栈
        if(*s=='('||*s=='['||*s=='{'){
            STPush(&st,*s);
        }
        else{  //右括号取栈顶左括号尝试匹配
            if(STEmpty(&st)){
                return false;
            }
            char top=STTop(&st);
            STPop(&st);
            //不匹配
            if((top=='('&&*s!=')')
            ||(top=='{'&&*s!='}')
            ||(top=='['&&*s!=']')){
                return false;
            }
        }
           ++s;
        }
        //栈不为空,说明左括号比右括号多,数量不匹配
        bool ret=STEmpty(&st);
        return ret;
    }

  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值