LeetCode.20有效括号
typedef char STDataType;
typedef struct Stack
{
STDataType* a;
int top ;
int capacity;
}ST ;
void StackInit(ST* ps);
void StackPush(ST* ps, STDataType data);
void StackPop(ST* ps);
STDataType StackTop(ST* ps);
int StackSize(ST* ps);
bool StackEmpty(ST* ps);
void StackDestroy(ST* ps);
void StackInit(ST* ps)
{
assert(ps);
ps->a = NULL;
ps->capacity = 0;
ps->top = 0;
}
void StackPush(ST* ps, STDataType data)
{
assert(ps);
if (ps->top == ps->capacity)
{
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
ST* tmp = (ST*)realloc(ps->a, sizeof(STDataType)*newcapacity);
if (tmp == NULL)
{
printf("fail:realloc StackPush");
exit(-1);
}
ps->a = tmp;
ps->capacity = newcapacity;
}
ps->a[ps->top] = data;
ps->top++;
}
void StackDestroy(ST* ps)
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->capacity = ps->top = 0;
}
void StackPop(ST* ps)
{
assert(ps);
assert(ps->top > 0);
ps->top--;
}
STDataType StackTop(ST* ps)
{
assert(ps);
assert(!StackEmpty(ps));
return ps->a[ps->top - 1];
}
bool StackEmpty(ST* ps)
{
assert(ps);
return ps->top == 0;
}
int StackSize(ST* ps)
{
assert(ps);
return ps->top;
}
bool isValid(char * s){
ST st;
StackInit(&st);
while(*s)
{
if(*s=='('||*s=='{'||*s=='[')
{
StackPush(&st,*s);
++s;
}
else{
if(StackEmpty(&st))
{
return false;
}
STDataType top=StackTop(&st);
StackPop(&st);
if(*s=='}'&&top!='{' || *s==']'&&top!='[' || *s==')'&&top!='(')
{
StackDestroy(&st);
return false;
}
else{
++s;
}
}
}
bool ret =StackEmpty(&st);
StackDestroy(&st);
return ret ;
}