4.1OJ题:括号匹配问题

本文解析了如何使用栈数据结构实现LeetCode上的有效括号问题,通过示例代码展示了如何检查输入字符串中括号的正确配对。通过递归栈操作确保左右括号的匹配规则和顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

力扣icon-default.png?t=LA92https://leetcode-cn.com/problems/valid-parentheses/点击上面网址可查看原题

题目

给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。

有效字符串需满足:

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

解答

首先我们先把栈的接口函数完善进去

typedef char STDataType;
typedef struct Stack{
    STDataType* a;
    int top;
    int capacity;
}ST;
void StackInit(ST* ps){
    assert(ps);
    ps->a=NULL;
    ps->top=0;
    ps->capacity=0;
}
void StackPush(ST* ps,STDataType x){
    assert(ps);
    if(ps->top==ps->capacity){
        int newcapacity=ps->capacity==0?4:ps->capacity*2;
        STDataType* tmp=(STDataType*)realloc(ps->a,sizeof(STDataType)*newcapacity);
        if(tmp==NULL){
            printf("realloc fail\n");
            exit(-1);
        }
        ps->a=tmp;
        ps->capacity=newcapacity;
    }
    ps->a[ps->top++]=x;
}
void StackPop(ST* ps){
    assert(ps);
    assert(ps->top>0);
    ps->top--;
}
STDataType StackTop(ST* ps){
    assert(ps);
    assert(ps->top>0);
    return ps->a[ps->top-1];
}
void StackDestroy(ST* ps){
    assert(ps);
    free(ps->a);
    ps->a=NULL;
    ps->top=0;
    ps->capacity=0;
}

然后在完善括号匹配函数的功能

bool isValid(char * s){
    ST st;
    StackInit(&st);
    for(int i=0;s[i]!='\0';++i){
        if(s[i]=='('||s[i]=='{'||s[i]=='['){
            StackPush(&st,s[i]);
        }else{
            if(st.top==0){
                StackDestroy(&st);
                return false;
            }
            if((s[i]==')'&&StackTop(&st)!='(')
             ||(s[i]=='}'&&StackTop(&st)!='{')
             ||(s[i]==']'&&StackTop(&st)!='[')){
                StackDestroy(&st);
                return false;
             }else{
                 StackPop(&st);
             }
        }
    }
    if(st.top==0){
        StackDestroy(&st);
        return true;
    }else{
        StackDestroy(&st);
        return false;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

少校0778

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值