当前位置:网站首页>【20. 有效的括号】
【20. 有效的括号】
2022-06-22 19:41:00 【爱吃榴莲的喵星人】
一、题目描述
二、做题思路
1.左括号,入栈
2.右括号,左括号出栈跟右括号匹配
三、题目代码
typedef char STDataType;
typedef struct Stack
{
STDataType* a;
int top;
int capacity;
}ST;
void StackInit(ST* ps)
{
assert(ps);
ps->a=NULL;
ps->top=0;
ps->capacity=0;
}
void StackDestroy(ST* ps)
{
assert(ps);
free(ps->a);
ps->a=NULL;
ps->top=ps->capacity=0;
}
void StackPush(ST* ps, STDataType x)
{
assert(ps);
if(ps->top==ps->capacity)
{
int newcapacity=(ps->capacity==0) ? 4 : 2*ps->capacity;
STDataType*tmp=(STDataType*)realloc(ps->a,sizeof(STDataType)*newcapacity);
if(tmp==NULL)
{
exit(-1);
}
else
{
ps->a=tmp;
ps->capacity=newcapacity;
}
}
ps->a[ps->top]=x;
ps->top++;
}
bool StackEmpty(ST* ps)
{
assert(ps);
return ps->top==0;
}
void StackPop(ST* ps)
{
assert(ps);
assert(!StackEmpty(ps));
ps->top--;
}
STDataType StackTop(ST* ps)
{
assert(ps);
return ps->a[ps->top-1];
}
int StackSize(ST* ps)
{
assert(ps);
return ps->top;
}
bool isValid(char * s){
ST st;
StackInit(&st);
while(*s)
{
if(*s=='('||*s=='{'||*s=='[')
{
StackPush(&st,*s);
s++;
}
else
{
//遇到右括号了,但是栈里面没有数据,说明
//前面没有左括号,不匹配,返回false s="]"
if(StackEmpty(&st))
{
//[{()}]],这种情况虽然栈是空但入过数据,栈是了开辟空间的
//所以要销毁,防止内存泄露
StackDestroy(&st);
return false;
}
STDataType top=StackTop(&st);
StackPop(&st);
if((*s == ')' && top != '(')
||(*s == '}' && top != '{')
||(*s == ']' && top != '['))
{
//如果s="[[}]",到这里栈里只剩下[
//防止内存泄露要销毁函数
StackDestroy(&st);
return false;
}
s++;
}
}
//如果栈不是空,说明栈中还有左括号未出
//没有匹配。返回是false s="["
bool ret=StackEmpty(&st);
StackDestroy(&st);
return ret;
}
以上是本篇文章的全部内容,如果文章有错误或者有看不懂的地方,多和喵博主交流。互相学习互相进步。如果这篇文章对你有帮助,可以给喵博主一个关注,你们的支持是我最大的动力。
边栏推荐
猜你喜欢
随机推荐
【文末送书】火遍全网的AI给老照片上色,这里有一份详细教程!
Oh, my God, it's a counter attack by eight part essay
AAAI 2022 | traditional Gan can be interpreted after modification, and the interpretability of convolution kernel and the authenticity of generated image are guaranteed
92-几个用match_recognize SQL写法示例
Lora technology -- Lora signal changes from data to Lora spread spectrum signal, and then from RF signal to data through demodulation
百家讲坛 雍正十三年(下部)
农产品期货开户
R language universalbank CSV "data analysis
Feign FAQ summary
阿里云视频点播播放出错,控制台访问出现code:4400
CVPR 2022 oral | video text pre training new SOTA, HKU and Tencent arc lab launched excuse task based on multiple-choice questions
【观察】软件行业创新进入“新周期”,如何在变局中开新局?
How to calculate yoy and mom in MySQL
扩展Ribbon支持Nacos权重的三种方式
LORA技术---LoRa信号从数据流变为LoRa扩频信号,再从射频信号通过解调变为数据
Notes d'apprentissage de golang - structure
访问成功但抛出异常:Could not find acceptable representation
He was in '98. I can't play with him
慕课5、服务发现-Nacos
Nestjs integrates config module and Nacos to realize configuration unification









