题目
大概步骤
假如所有括号都在字符串S中
遍历字符串S
如果S字符开头是右括号将字符串S中的字符依次放入栈中如果遇到左括号将栈顶字符比较如果匹配删除栈顶字符继续遍历字符串遇到右括号就放入栈顶遇到左括号就比较
如果一开始遇到的就是左括号那么结束遍历返回false
代码如下
typedef char StDateType;
typedef struct Stack
{
StDateType* a;
int top;
int capacity;
}stack;
void StackInit(stack* ps)
{
assert(ps);
ps->a = NULL;
ps->top = 0;
ps->capacity = 0;
}
void StackPush(stack* ps, StDateType x)
{
assert(ps);
if (ps->top == ps->capacity)
{
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
StDateType* temp = (StDateType*)realloc(ps->a, newcapacity * 2);
if (temp == NULL)
{
perror("realloc fail");
return;
}
ps->capacity = newcapacity;
ps->a = temp;
}
ps->a[ps->top] = x;
ps->top++;
}
int StackEmpty(stack* ps)
{
assert(ps);
return ps->top == 0;
}
void StackPop(stack* ps)
{
assert(ps);
assert(ps->top > 0);
ps->top--;
}
StDateType Stacktop(stack* ps)
{
assert(ps);
assert(ps->top > 0);
return(ps->a[ps->top - 1]);
}
void stackDestory(stack* ps)
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->capacity = 0;
ps->top = 0;
}
bool isValid(char* s) {
stack ST;
StackInit(&ST);
while(*s)
{
if(*s=='('||*s=='{'||*s=='[')
{
StackPush(&ST,*s);
}
else
{
if(StackEmpty(&ST))
{
stackDestory(&ST);
return false;
}
char top=Stacktop(&ST);
StackPop(&ST);
if((top=='('&&*s!=')')||(top=='['&&*s!=']')||(top=='{'&&*s!='}'))
{
stackDestory(&ST);
return false;
}
}
s++;
}
bool ret=StackEmpty(&ST);
stackDestory(&ST);
return ret;
}