朋友们,今天,我们讲解 一道用栈区实现括号匹配问题!!
---> 给定一个只包括 ‘( ’ , ‘ )’ ,‘ { ’, ‘ } ’, ‘ [ ’ , ']' 的字符串 s, 判断字符串是否有效。
并且有效字符串需要满足:
1.左括号必须用相同类型的右括号进行匹配
2.左括号必须以正确的顺序闭合。
3.每个右括号都有一个对应的相同类型的左括号。
其中,还有一个附加条件:
s 仅有 ‘()’, ‘{}’, ‘[ ]’,三样组成
现在,我们可以上手代码了!!其实,前面期刊中,我们已经学习过 栈区 的创建过程!!这个时候,再多说一句废话,我们完全可以当个 CV 工程师给拷贝过来!!想想蛮爽的!!😊
代码如下:
#include <stdio.h>
#include <stdlib.h>
typedef char STDataType;
typedef struct Stack
{
STDataType* a;
int capcity;
int top;
}ST;
//初始化
void STInitial(ST* ps)
{
ps ->a = (STDataType*)malloc(STDataType);
if(ps ->a == NULL)
{
perror("malloc::fail");
return ;
}
int capcity = 4;
int top = 0; //top = 0 是栈顶元素的下一个位置
//top = -1 是栈顶元素的位置
}
//销毁
void STDestroy(ST* ps)
{
assert(ps);
assert(!STEmpty(ps));
free(ps ->a);
ps ->a = NULL;
ps ->capcity = 0;
ps ->top = 0;
}
//压栈
void STPush(ST* ps, STDataType x)
{
if(ps ->capcity == ps ->top)
{
STDataType* tamp = (STDataType*)realloc(ps ->a, sizeof(STDataType) * ps ->capcity * 2);
if(tamp == NULL)
{
perror("realloc::fail");
return ;
}
ps ->a = tamp;
ps ->capcity *= 2;
}
// ps ->a[ps ->top] = x;
// ps ->top++;
ps ->a[ps ->top++] = x;
}
//出栈
void STPop(ST* ps)
{
assert(ps);
assert(!STEmpty(ps));
ps ->top--;
}
//栈顶元素
STDataType STTop(ST* ps)
{
assert(ps);
assert(!STEmpty(ps));
return ps ->a[ps ->top - 1];
}
//布尔判空
bool STEmpty(ST* ps)
{
assert(ps);
return ps ->top == 0;
}
//用布尔实现括号匹配
bool isValid(char* s)
{
ST st;
STInitial(&st);
while(*s)
{
if(*s == '(' || *s == '{' || *s == '[')
{
STPush(&st);
}
else
{
if(STEmpty(&st))
return false;
char top = STTPop(&st);
STPop(&st);
if(*s == '(' && top != ')' || *s == '{' && top != '}' && *s == '[' && top != ']')
return false;
}
++*s;
}
bool ret = STEmpty(&st);
STDestroy(&st);
return ret;
}
此外,需注意一点儿小细节,就是重定义的那个部分,需要将 int 改成 char, 我想没有哪位朋友有疑问吧!!
或者说,我这纯属是一句废话!!
好了,各位朋友。今天的讲解已完成!!
感谢阅读!!😊😊