有效的括号题解

首先给出思路:

1.这道题要调用栈,详情可以看:https://blog.csdn.net/xpcxpt/article/details/148481903?spm=1001.2014.3001.5501

2.我们利用栈后进先出的特点,遇到左括号就入栈,遇到右括号就取栈顶的括号尝试匹配

在遇到左括号的时候,有可能是 ( , [ , { 中的任意一种,所以说我们都要写到,遇到其中之一,就直接入栈:

那如果遇到的是右括号,就用我们的思路:遇到右括号就取栈顶的括号尝试匹配。这里有多种情况

第一种:给的字符串为空,那么我们可以调用判空函数,如果是空,直接返回false

第二种:有额外的括号游离于匹配的括号之外,那我们也可以调用判空函数,如果不为空,代表有游离的括号,也返回false

第三种:恰好数量匹配,那我们就一个一个看是否匹配,如果匹配,就走到字符串下一个字符继续看,直到遍历完字符串

具体代码如下:

cpp 复制代码
typedef char stacktype;
typedef struct Stack
{
	stacktype* a;//动态数组
	int top;    //个数
	int capacity;//空间
}ST;

void STInit(ST* pst);//初始化
void STDestroy(ST* pst);//销毁
void STPush(ST* pst, stacktype x);//插入 入栈
void STPop(ST* pst);//删除 出栈
stacktype STTop(ST* pst);//获取栈顶数据
bool STEmpty(ST* pst);//判断栈是否为空
int STSize(ST* pst);//判断栈的数据个数

void STInit(ST* pst)//初始化
{
	assert(pst);
	pst->a = NULL;
	pst->top = 0;//基于size指向的是栈顶数据的下一个位置
	pst->capacity = 0;
}

void STDestroy(ST* pst)//销毁
{
	assert(pst);
	free(pst->a);//free掉
	pst->a = NULL;//置为空,防止变成野指针
	pst->top = 0;
	pst->capacity = 0;
}

void STPush(ST* pst, stacktype x)//插入 入栈
{
	assert(pst);
	//扩容
	if (pst->top == pst->capacity)
	{
		int newcapacity = pst->capacity == 0 ? 4 : pst->capacity * 2;
		stacktype* tmp = (stacktype*)realloc(pst->a, newcapacity * sizeof(stacktype));
		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);//top是非负数
	pst->top--;//删除一个
}
stacktype 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;//从0开始的,所以返回size的大小-1,也就是下表从0-top-1,一共top个
}

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);
    STDestroy(&st);//销毁栈
    return ret;
}
相关推荐
vibecoding日记4 小时前
双非如何快速入职字节等大厂大模型?真实案例分析:推理优化和投机解码
算法·求职·大模型工程师
yszaygr21386 小时前
Verilog参数化游程编码RLE模块
算法
望易7 小时前
刚设计的大模型架构-双域耦合认知框架
算法·架构
复杂网络10 小时前
多个 Claude Code 与多个 Codex 协同工作:设计与实现方案
算法
HjhIron1 天前
面试常客:字符串算法从入门到进阶
算法·面试
吴佳浩1 天前
DeepSeek DSpark:Confidence-Scheduled Speculative Decoding 技术解析
人工智能·算法·deepseek
触底反弹1 天前
🧠 搞懂 Token,才算真正入门大模型——从分词原理到 Embedding 语义实战
javascript·人工智能·算法
vivo互联网技术1 天前
ICLR 2026 | 基于后验采样的图像恢复方法LearnIR:人脸去阴影、去雾
人工智能·算法·aigc
浮生望1 天前
JS字符串与回文算法:从包装类到双指针的面试进阶之路
javascript·算法