有效的括号
点击链接答题
思路:
定义一个指针
ps
遍历字符串若
ps
遍历到的字符为左括号,入栈若
ps
遍历到的字符为右括号,取栈顶元素与ps
进行比较,
栈顶元素 匹配 *ps
,出栈,ps++
栈顶元素 不匹配 *ps
,返回false
代码:
//定义栈的结构
typedef char STDataType;
typedef struct Stack {
STDataType* arr;
int capacity;//栈的空间大小
int top;//栈顶
}ST;
//栈的初始化
void STInit(ST* ps) {
assert(ps);
ps->arr = NULL;
ps->capacity = ps->top = 0;
}
//栈的销毁
void STDestory(ST* ps) {
assert(ps);
if (ps->arr) {
free(ps->arr);
}
ps->arr = NULL;
ps->top = ps->capacity = 0;
}
//栈顶---入数据,出数据
//入数据
void StackPush(ST* ps, STDataType x) {
assert(ps);
//1.判断空间是否足够
if (ps->capacity == ps->top) {
int newCapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;//增容
STDataType* tmp = (STDataType*)realloc(ps->arr, newCapacity * sizeof(STDataType));
if (tmp == NULL) {
perror("relloc fail!");
exit(1);
}
ps->arr = tmp;
ps->capacity = newCapacity;
}
//空间足够
ps->arr[ps->top++] = x;
}
//判断栈是否为空
bool StackEmpty(ST* ps) {
assert(ps);
return ps->top == 0;
}
//出数据
void StackPop(ST* ps) {
assert(ps);
assert(!StackEmpty(ps));//栈为空报错
--ps->top;
}
//获取栈中有效元素个数
int STSize(ST* ps){
assert(ps);
return ps->top;
}
//取栈顶元素
STDataType StackTop(ST* ps) {
assert(ps);
assert(!StackEmpty(ps));
return ps->arr[ps->top - 1];
}
bool isValid(char* s) {
ST st;
//初始化
STInit(&st);
//遍历字符串s
char* ps = s;
while(*ps != '\0'){
//左括号,入栈
if(*ps == '(' || *ps == '[' || *ps == '{'){
StackPush(&st, *ps);
}
else{//右括号,和栈顶元素比较是否匹配
//栈为空,直接返回false
if(StackEmpty(&st)){
return false;
}
//栈不为空才能取栈顶元素
char ch = StackTop(&st);
if((*ps == ')' && ch == '(')
|| (*ps == ']' && ch == '[')
|| (*ps == '}' && ch == '{') ){
StackPop(&st);
}
else{
//不匹配
STDestory(&st);
return false;
}
}
ps++;
}
bool ret = StackEmpty(&st) == true;//如果为空,返回true
//销毁
STDestory(&st);
return ret;
}