思想:左括号入栈,右括号出栈顶与左括号匹配。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
typedef char STDataType;
typedef struct stack{
STDataType*a;
int top;
int capacity;
}ST;
//初始化栈
void STInit(ST*pst){
assert(pst);
pst->top=pst->capacity=0;
pst->a=NULL;
}
//入栈
void STPush(ST*pst,STDataType x){
assert(pst);
if(pst->top==pst->capacity){ //空间不够进行增容
int newcapacity=pst->capacity==0?4:pst->capacity*2;
STDataType*tmp=(STDataType*)realloc(pst->a,newcapacity*sizeof(STDataType));
if(tmp==NULL){
perror("realloc fail");
return;
}
pst->a=tmp;
pst->capacity=newcapacity;
}
pst->a[pst->top]=x;
pst->top++;
}
//出栈
void STPop(ST*pst){
assert(pst);
assert(pst->top>0);
pst->top--;
}
//取栈顶元素
STDataType STTop(ST*pst){
assert(pst);
assert(pst->top>0);
return pst->a[pst->top-1];
}
//判空
bool STEmpty(ST*pst){
assert(pst);
return pst->top==0;
}
bool isValid(char*s){
ST st;
STInit(&st);
while(*s){
//左括号入栈
if(*s=='('||*s=='['||*s=='{'){
STPush(&st,*s);
}
else{ //右括号取栈顶左括号尝试匹配
if(STEmpty(&st)){
return false;
}
char top=STTop(&st);
STPop(&st);
//不匹配
if((top=='('&&*s!=')')
||(top=='{'&&*s!='}')
||(top=='['&&*s!=']')){
return false;
}
}
++s;
}
//栈不为空,说明左括号比右括号多,数量不匹配
bool ret=STEmpty(&st);
return ret;
}