

首先给出思路:
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;
}