这里,我提供一种用栈来解决的方法:
思路:栈的结构是先进后出,这样我们就可以模拟栈结构了,如果是‘(’、‘{’、‘[’任何一种,直接push进栈就可以了,如果是‘}’、‘)’、‘]’任何一种就开始判断,看栈pop的是否和对应的字符匹配。
文章来源地址https://www.toymoban.com/news/detail-677329.html
下面是源码:
typedef char STDateType;
typedef struct Stack
{
STDateType* a;
int top;
int capacity;
}Stack;
void StackInit(Stack* ps);
void StackPush(Stack* ps, STDateType x);
void StackPop(Stack* ps);
STDateType StackTop(Stack* ps);
int StackSize(Stack* ps);
bool StackEmpty(Stack* ps);
void StackDestroy(Stack* ps);
void StackInit(Stack* ps)
{
assert(ps);
ps->a = NULL;
ps->capacity = ps->top = 0;
}
void StackPush(Stack* ps, STDateType x)
{
assert(ps);
if (ps->top == ps->capacity)
{
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
STDateType* tmp = (STDateType*)realloc(ps->a, sizeof(STDateType) * newcapacity);
if (tmp == NULL)
{
perror("realloc fail");
exit(-1);
}
ps->a = tmp;
ps->capacity = newcapacity;
}
ps->a[ps->top] = x;
ps->top++;
}
void StackPop(Stack* ps)
{
assert(ps);
--ps->top;
}
STDateType StackTop(Stack* ps)
{
assert(ps);
return ps->a[ps->top - 1];
}
int StackSize(Stack* ps)
{
assert(ps);
return ps->top;
}
bool StackEmpty(Stack* ps)
{
assert(ps);
return ps->top == 0;
}
void StackDestroy(Stack* ps)
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->top = ps->capacity = 0;
}
bool isValid(char * s){
Stack st;
StackInit(&st);
char top;
while(*s)
{
if((*s == '(') || (*s == '[') || (*s == '{'))
{
StackPush(&st,*s);
}else
{
if(StackEmpty(&st))
{
StackDestroy(&st);
return false;
}
top = StackTop(&st);
StackPop(&st);
if((*s == ']' && top != '[')
|| (*s == '}' && top != '{')
|| (*s == ')' && top != '('))
{
StackPop(&st);
StackDestroy(&st);
return false;
}
}
++s;
}
bool ret = StackEmpty(&st);
StackDestroy(&st);
return ret;
}
文章来源:https://www.toymoban.com/news/detail-677329.html
到了这里,关于LeetCode——有效的括号的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!