20.有效括号

在这里插入图片描述
在这里插入图片描述

typedef int STDataType;

typedef struct Stack
{
	STDataType* a;
	int top;
	int capacity;
}ST;

// 初始化和销毁
void STInit(ST* pst);
void STDestroy(ST* pst);

// 入栈  出栈
void STPush(ST* pst, STDataType x);
void STPop(ST* pst);

// 取栈顶数据
STDataType STTop(ST* pst);

// 判空
bool STEmpty(ST* pst);
// 获取数据个数
int STSize(ST* pst);


// 初始化和销毁
void STInit(ST* pst)
{
	assert(pst);
	pst->a = NULL;
	pst->top = 0;
	pst->capacity = 0;

}
void STDestroy(ST* pst)
{
	assert(pst);
	free(pst->a);
	pst->a = NULL;
	pst->capacity = pst->top = 0;
}

// 入栈  出栈
void STPush(ST* pst, STDataType x)
{
	if (pst->top == pst->capacity)
	{
		assert(pst);
		int newcapacity = pst->capacity == 0 ? 4 : 2 * (pst->capacity);
		STDataType* tmp = (STDataType*)realloc(pst->a, newcapacity * sizeof(STDataType));;
		if (tmp == NULL)
		{
			perror(malloc);
		}
		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;

}
// 获取数据个数
int STSize(ST* pst)
{
	assert(pst);

	return pst->top;
}


bool isValid(char* s) {
    ST st;
    STInit(&st);
    while(*s)
    {
        //左括号入栈
        if(*s=='(' || *s=='[' || *s=='{')
        {
            STPush(&st,*s);
        }
        else
        {
            if(STEmpty(&st))
            {
                STDestroy(&st);
                return false;
            }
            //取栈顶与右括号匹配
            char top=STTop(&st);
            STPop(&st);

            if((top=='(' && *s!=')')
            || (top=='[' && *s!=']')
            || (top=='{' && *s!='}'))
            {
                STDestroy(&st);
                return false;
            }
        }
        ++s;
    }

    bool ret=STEmpty(&st);
    STDestroy(&st);

    return ret;
    
}

我们需要判断一对括号是否匹配,匹配的话就返回turn,失败就返回false。我们用栈来实现这个,栈是先进后出的,如果是左括号就入栈,如果是右括号就让栈里的左括号与右括号进行匹配,如果匹配上就继续匹配下一个。这里有特殊情况,如果刚开始入栈的是右括号肯定不匹配,直接返回false。还有一种情况,就是遍历完一遍后还有左括号,这时就要判断一下栈是否为空了。

注意:用c语言来实现要添加实现栈的代码。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值