每日一题——栈的OJ题(有效的括号)

有效的括号:

20. 有效的括号 - 力扣(LeetCode)

题目:

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

有效字符串需满足:

左括号必须用相同类型的右括号闭合。

左括号必须以正确的顺序闭合。

每个右括号都有一个对应的相同类型的左括号。

示例 1:

复制代码
输入:s = "()"
输出:true

示例 2:

复制代码
输入:s = "()[]{}"
输出:true

示例 3:

复制代码
输入:s = "(]"
输出:false

提示:

  • 1 <= s.length <= 104
  • s 仅由括号 '()[]{}' 组成

分析:

条件

左括号必须用相同类型的右括号闭合。

左括号必须以正确的顺序闭合。

每个右括号都有一个对应的相同类型的左括号。

输入: s = "()\[\]{}"

流程图:

为了方便分析:加大一点点剂量

**输入:**s = "[{}{{(}})"

流程图:逐步分析

第一次

第二次

每次取栈顶数据与之匹配

注:这里的{,并不是上一步的{,上一步的{,因为匹配所以pop掉了

实现:

注:实现中的top与图片上top功能不同,请注意辨别

图片中的top是取右括号(因为为数组,所以有括号的值无需变量接收),而下方的top是取栈顶的数据。

这里运用到栈的思想,所以这里先要实现栈

深入了解栈(走进栈的世界)-CSDN博客

包含栈

复制代码
// 支持动态增长的栈
typedef char STDataType;
typedef struct Stack
{
	STDataType* a;
	int top;		// 栈顶大小
	int capacity;  // 容量 
}Stack;


// 初始化栈 
void StackInit(Stack* ps);
// 入栈 
void StackPush(Stack* ps, STDataType data);
// 出栈 
void StackPop(Stack* ps);
// 获取栈顶元素 
STDataType StackTop(Stack* ps);
// 获取栈中有效元素个数 
int StackSize(Stack* ps);
// 检测栈是否为空,如果为空返回非零结果,如果不为空返回0 
int StackEmpty(Stack* ps);
// 销毁栈 
void StackDestroy(Stack* ps);
void STpop(Stack* ps);
bool stempty(Stack* ps);

// 初始化栈 
void StackInit(Stack* ps){
	assert(ps);
	ps->a = NULL;
	ps->capacity = 0;
	ps->top = 0;
}

bool stempty(Stack* ps);

// 入栈 
void StackPush(Stack* ps, STDataType data) {
	assert(ps);
	//扩容
	if (ps->top == ps->capacity) {
		int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		STDataType* tmp =(STDataType*) realloc(ps->a, newcapacity * sizeof(STDataType));
		if (tmp == NULL) {
			perror("realloc fail!");
			exit(1);
		}
		ps->a = tmp;
		ps->capacity = newcapacity;

	}

	ps->a[ps->top] = data;
	ps->top++;

}

// 出栈 
void StackPop(Stack* ps) {
	assert(ps);
	while (ps->top > 0) {
	STDataType s = StackTop(ps);
	printf("%d", s);
	}
}

void STpop(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);
	//return ps->top == 0 ? 1 : 0;
	return ps->top == 0;
}
// 销毁栈 
void StackDestroy(Stack* ps) {
	assert(ps);
	free(ps->a);
	ps->a = NULL;
	ps->capacity = ps->top = 0;
}

括号匹配

复制代码
bool isValid(char* s) {
 Stack st;
 StackInit(&st);
 while(*s){
    //左括号入栈
    if(*s=='{' || *s=='[' || *s=='('){
        StackPush(&st,*s);
    }
    else{
        //取栈顶元素,与右括号匹配
        char top=StackTop(&st);
        STpop(&st);
        if((top=='['&&*s!=']')||(top=='{'&&*s!='}')||(top=='('&&*s!=')')){
            StackDestroy(&st);
            return false;
        }

    }
    ++s;
 }

return true

}

分析问题:

栈剩余

当数组走完,右括号恰好能完全匹配,但是呢,栈却还存留一个

问题解决

为了解决这个问题,我们需要判NULL

复制代码
bool ret = StackEmpty(&st);
//循环走完,判断栈是否还有剩余
 StackDestroy(&st);
 return ret;
}

访问NULL和首为右括号

对于传址问题,这是很常见的

复制代码
//取栈顶元素,与右括号匹配
        char top=StackTop(&st);
        //我们会发现,这里对栈的传址
        STpop(&st);
        if((top=='['&&*s!=']')||(top=='{'&&*s!='}')||(top=='('&&*s!=')')){
            StackDestroy(&st);
            return false;

问题解决

复制代码
 if(StackEmpty(&st)){
            StackDestroy(&st);
            return false;
        }

完善代码

复制代码
// 支持动态增长的栈
typedef char STDataType;
typedef struct Stack
{
	STDataType* a;
	int top;		// 栈顶大小
	int capacity;  // 容量 
}Stack;


// 初始化栈 
void StackInit(Stack* ps);
// 入栈 
void StackPush(Stack* ps, STDataType data);
// 出栈 
void StackPop(Stack* ps);
// 获取栈顶元素 
STDataType StackTop(Stack* ps);
// 获取栈中有效元素个数 
int StackSize(Stack* ps);
// 检测栈是否为空,如果为空返回非零结果,如果不为空返回0 
int StackEmpty(Stack* ps);
// 销毁栈 
void StackDestroy(Stack* ps);
void STpop(Stack* ps);
bool stempty(Stack* ps);

// 初始化栈 
void StackInit(Stack* ps){
	assert(ps);
	ps->a = NULL;
	ps->capacity = 0;
	ps->top = 0;
}

bool stempty(Stack* ps);

// 入栈 
void StackPush(Stack* ps, STDataType data) {
	assert(ps);
	//扩容
	if (ps->top == ps->capacity) {
		int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		STDataType* tmp =(STDataType*) realloc(ps->a, newcapacity * sizeof(STDataType));
		if (tmp == NULL) {
			perror("realloc fail!");
			exit(1);
		}
		ps->a = tmp;
		ps->capacity = newcapacity;

	}

	ps->a[ps->top] = data;
	ps->top++;

}

// 出栈 
void StackPop(Stack* ps) {
	assert(ps);
	while (ps->top > 0) {
	STDataType s = StackTop(ps);
	printf("%d", s);
	}
}

void STpop(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);
	//return ps->top == 0 ? 1 : 0;
	return ps->top == 0;
}
// 销毁栈 
void StackDestroy(Stack* ps) {
	assert(ps);
	free(ps->a);
	ps->a = NULL;
	ps->capacity = ps->top = 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);
        STpop(&st);
        if((top=='['&&*s!=']')||(top=='{'&&*s!='}')||(top=='('&&*s!=')')){
            StackDestroy(&st);
            return false;
        }

    }
    ++s;
 }
 bool ret = StackEmpty(&st);
 StackDestroy(&st);
 return ret;
}

相关推荐
YukiRinLL1 分钟前
查找与排序算法:复杂度、稳定性
数据结构·算法·排序算法
ACP广源盛139246256739 小时前
Type-C 扩展坞方案选型笔记:DP1.4 转 HDMI2.0 桥接方案评估@ACP
笔记·硬件架构·hdmi·国产芯片·扩展坞
徐小夕9 小时前
花了3个月,我们做了一款 AI 版的“飞书文档”
前端·算法·github
Robert--cao9 小时前
移动底盘与机械臂联合规划:开源算法与工程实现
算法
小豆庄10 小时前
Mac 上给视频人脸打码:本地工具的依赖、追踪与推理管线
算法·视觉检测·视频·敏捷流程·纹理贴图
星夜离尘5610 小时前
MATLAB 工程实验:从相邻块均值手写重叠 Allan 偏差,数清有效项
算法·matlab·均值算法
careathers11 小时前
【数据结构】从堆到 PriorityQueue:手写一个优先级队列
数据结构
ss27311 小时前
AI时代首先数据库-PostgreSQL实战笔记 | 22 PostgreSQL实例与集群
数据库·笔记·postgresql
ss27311 小时前
AI时代首先数据库-PostgreSQL实战笔记 | 21 PostgreSQL进程与内存架构介绍
数据库·笔记·postgresql
水饺编程12 小时前
第2章:Linux 基础,切换到超级用户
linux·c语言·汇编