
leetcode-有效的括号-26
发布日期:2021-05-04 18:21:47
浏览次数:28
分类:原创文章
本文共 2013 字,大约阅读时间需要 6 分钟。
题目要求
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串 s ,判断字符串是否有效。有效字符串需满足,左括号必须用相同类型的右括号闭合,左括号必须以正确的顺序闭合。
思路
利用栈的后进先出原理(LIFO),当检测到前括号的时候,进行括号的入栈操作,然后当检测出来对应的后括号时,进行出栈操作进行匹配,如果匹配不上直接返回假。
图解
代码实现
typedef char SLDataType;typedef struct SeqList{ SLDataType* a; int top; int capacity;}Stack;//栈的初始化void StackInit(Stack* pst);//栈的销毁void StackDestory(Stack* pst);//增加栈顶元素void StackPush(Stack* pst, SLDataType x);//移除栈顶元素void StackPop(Stack* pst);//返回栈中元素的数目int StackSize(Stack* pst);//返回栈顶元素SLDataType StackTop(Stack* pst);//栈内判空int StackEmpty(Stack* pst);//栈的初始化void StackInit(Stack* pst){ assert(pst); pst->a = (SLDataType*)malloc(sizeof(SLDataType)* 4); pst->top = 0; pst->capacity = 4;}//栈的销毁void StackDestory(Stack* pst){ assert(pst); free(pst->a); pst->a = NULL; pst->top = pst->capacity = 0;}//增加栈顶元素void StackPush(Stack* pst, SLDataType x){ assert(pst); if (pst->top == pst->capacity) { SLDataType* tmp = realloc(pst->a, pst->capacity * 2 * sizeof(SLDataType)); if (tmp == NULL) { printf("relloc fail\n"); exit(-1); } pst->a = tmp; pst->capacity *= 2; } pst->a[pst->top] = x; pst->top++;}//移除栈顶元素void StackPop(Stack* pst){ assert(pst); assert(!StackEmpty(pst)); pst->top--;}//返回栈中元素的数目int StackSize(Stack* pst){ assert(pst); return pst->top;}//返回栈顶元素SLDataType StackTop(Stack* pst){ assert(pst); assert(!StackEmpty(pst)); return pst->a[pst->top - 1];}//栈内判空int StackEmpty(Stack* pst){ assert(pst); return pst->top == 0 ? 1 : 0;}bool isValid(char * s){ Stack st; StackInit(&st); while (*s) { if (*s == '[' || *s == '(' || *s == '{') { StackPush(&st, *s); ++s; } else { if (StackEmpty(&st)) { return false; } char top = StackTop(&st); StackPop(&st); if (*s == ']' && top != '[') { StackDestory(&st); return false; } if (*s == '}' && top != '{') { StackDestory(&st); return false; } if (*s == ')' && top != '(') { StackDestory(&st); return false; } ++s; } } if (StackEmpty(&st)) { StackDestory(&st); return true; } StackDestory(&st); return false;}