括号匹配问题

题目:

代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <stdbool.h>

typedef char STDataType;

typedef struct Stack
{
	STDataType* a;
	int top;		// 栈顶
	int capacity;  // 容量 
}Stack;

// 初始化栈 
void StackInit(Stack* ps)
{
	assert(ps);

	ps->a = NULL;//可开可不开
	ps->top = 0;//top初始化为0或者-1都可以,只是a[ps->top]的意义有区别,这里top指向栈顶的下一个位置,也可以看做栈里的元素个数
	ps->capacity = 0;
}

// 入栈 
void StackPush(Stack* ps, STDataType data)
{
	assert(ps);

	if (ps->top == ps->capacity)//空间已满
	{
		int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;//容量为0则初始开辟4个空间,如果不为0则2倍扩容
		STDataType* tmp = (STDataType*)realloc(ps->a,sizeof(STDataType) * newcapacity);
		if (NULL == tmp)//扩容失败的情况
		{
			perror("realloc fail!");
			return;
		}
		ps->a = tmp;
		ps->capacity = newcapacity;
	}

	ps->a[ps->top++] = data;
}
// 出栈 
void StackPop(Stack* ps)
{
	assert(ps);
	assert(ps->top > 0);//

	ps->top--;
}

// 获取栈顶元素 
STDataType StackTop(Stack* ps)
{
	assert(ps);
	assert(ps->top > 0);

	return ps->a[ps->top - 1];
}

// 获取栈中有效元素个数 
int StackSize(Stack* ps)
{
	assert(ps);

	return ps->top;
}

// 检测栈是否为空,如果为空返回非零结果,如果不为空返回0 
int StackEmpty(Stack* ps)
{
	assert(ps);
	
	//if (0 == ps->top)
	//	return 1;
	//else
	//	return 0;

	return ps->top == 0;
}

// 销毁栈 
void StackDestroy(Stack* ps)
{
	assert(ps);

	free(ps->a);
	ps->a = NULL;
	ps->top = ps->capacity = 0;
}

//整体思想:左括号入栈,右括号出栈
bool isValid(char* s) 
{
    //先构造出栈
    Stack ST;
    StackInit(&ST);

    //建立循环遍历字符串
    while(*s)
    {
        if('('==*s||'['==*s||'{'==*s)//检测到左括号则入栈
            StackPush(&ST,*s);
        else//检测到右括号,匹配则左括号出栈,不匹配直接返回false
        {
            if(StackEmpty(&ST))//栈为空,没有左括号
            {
                StackDestroy(&ST);//不销毁会造成内存泄漏
                return false;
            }

            char top = StackTop(&ST);
            StackPop(&ST);

            if(*s==')'&&top!='('
            ||*s=='}'&&top!='{'
            ||*s==']'&&top!='[' )//不匹配则直接返回false
            {
                StackDestroy(&ST);
                return false;
            }

        }
        s++;//切换下一个字符
    }
    //栈为空则全都匹配上了,不为空则就还有左括号没有匹配上
    bool ret = StackEmpty(&ST);
    StackDestroy(&ST);
    return ret;
}

结果:

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值