思路
有效的括号,这个题目用到的是栈,他就是运用到的他的先进后出的特点,我们拿图来分析一下吧。
假如输入了这么一串字符,然后我们创建了一个空栈,我们如果碰到了左括号,那就进栈,如果碰到了右括号,那么就说明左括号都进栈了,那碰到了右括号,就将右括号与相近的左括号匹配。
但是我们将要思考一个问题,如果右括号与左括号匹配那又能怎么样呢,也并不能说明所有的有括号都能匹配,所以我们的解决方案就是当不匹配时返回false。这个方法还是蛮巧妙的,我们匹配一个就将那个匹配过的左括号出栈,直到全部都匹配完,这个所有括号就都是成对的了,返回true。
代码实现
#pragma once
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef char STDataType;
typedef struct Stack {
STDataType* a;
int top;
int capacity;
} ST;
// 初始化和销
void STInit(ST* pst);
void STDestroy(ST* pst);
// 入栈和出栈
void STPush(ST* pst, STDataType x);
void STPop(ST* pst);
// 取栈顶的数据
STDataType STTop(ST* pst);
// 判空
bool STEmpty(ST* pst);
// 获取栈数据个数
int STSize(ST* pst);
// 初始化和销毁
void STInit(ST* pst) {
assert(pst);
pst->a = NULL;
pst->capacity = 0;
pst->top = 0;
}
void STDestroy(ST* pst) {
assert(pst);
free(pst->a);
pst->a = NULL;
pst->capacity = 0;
pst->top = 0;
}
// 入栈和出栈
void STPush(ST* pst, STDataType x) {
assert(pst);
if (pst->top == pst->capacity) {
int newcapacity = pst->capacity == 0 ? 4 : pst->capacity * 2;
STDataType* tmp =
(STDataType*)realloc(pst->a, newcapacity * sizeof(STDataType));
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);
pst->top--;
}
// 取栈顶的数据
STDataType 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;
}
因为C语言的是不会自带栈的,所以我们要自己写一个栈,那我们就复制之前写过的栈,把.h 和 .c文件复制过来就可以了。
这就是整个代码的样子,整体思路就是:如果这个字符串解引用的字符是左括号,那就进栈,否则(右括号)就与栈里的栈顶的数据相匹配,一旦遇到不匹配的,那就返回false,还有一种特殊情况,就是左括号与右括号的数量不匹配,就有可能造成else走完了,并且都匹配,但是左括号剩了一个,所以出循环的时候要判断一下栈里还有没有数据。