栈:括号匹配问题

题目

大概步骤

假如所有括号都在字符串S中

遍历字符串S

如果S字符开头是括号将字符串S中的字符依次放入栈中如果遇到左括号将栈顶字符比较如果匹配删除栈顶字符继续遍历字符串遇到右括号就放入栈顶遇到左括号就比较

如果一开始遇到的就是左括号那么结束遍历返回false

代码如下

typedef char StDateType;
typedef struct Stack
{
	StDateType* a;
	int top;
	int capacity;
}stack;
void StackInit(stack* ps)
{
	assert(ps);
	ps->a = NULL;
	ps->top = 0;
	ps->capacity = 0;
}
void StackPush(stack* ps, StDateType x)
{
	assert(ps);
	if (ps->top == ps->capacity)
	{
		int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		StDateType* temp = (StDateType*)realloc(ps->a, newcapacity * 2);
		if (temp == NULL)
		{
			perror("realloc fail");
			return;
		}
		ps->capacity = newcapacity;
		ps->a = temp;
	}
	ps->a[ps->top] = x;
	ps->top++;
}
int StackEmpty(stack* ps)
{
	assert(ps);
	return ps->top == 0;
}
void StackPop(stack* ps)
{
	assert(ps);
	assert(ps->top > 0);
	ps->top--;
}
StDateType Stacktop(stack* ps)
{
	assert(ps);
	assert(ps->top > 0);
	return(ps->a[ps->top - 1]);
}
void stackDestory(stack* ps)
{
	assert(ps);
	free(ps->a);
	ps->a = NULL;
	ps->capacity = 0;
	ps->top = 0;
}
bool isValid(char* s) {
    stack ST;
    StackInit(&ST);
    while(*s)
    {
        if(*s=='('||*s=='{'||*s=='[')
        {
            StackPush(&ST,*s);
        }
        else
        {
            if(StackEmpty(&ST))
            {
                stackDestory(&ST);
                return false;
            }
            char top=Stacktop(&ST);
            StackPop(&ST);
            if((top=='('&&*s!=')')||(top=='['&&*s!=']')||(top=='{'&&*s!='}'))
            {
                stackDestory(&ST);
                return false;
            }
        }
        s++;
    }
    bool ret=StackEmpty(&ST);
    stackDestory(&ST);
    return ret;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值