typedef int STDataType;
typedef struct Stack
{
STDataType* a;
int top;
int capacity;
}ST;
// 初始化和销毁
void STInit(ST* pst);
void STDestroy(ST* pst);
// 入栈 出栈
void STPush(ST* pst, STDataType x);
void STPop(ST* pst);
// 取栈顶数据
STDataType STTop(ST* pst);
// 判空
bool STEmpty(ST* pst);
// 获取数据个数
int STSize(ST* pst);
// 初始化和销毁
void STInit(ST* pst)
{
assert(pst);
pst->a = NULL;
pst->top = 0;
pst->capacity = 0;
}
void STDestroy(ST* pst)
{
assert(pst);
free(pst->a);
pst->a = NULL;
pst->capacity = pst->top = 0;
}
// 入栈 出栈
void STPush(ST* pst, STDataType x)
{
if (pst->top == pst->capacity)
{
assert(pst);
int newcapacity = pst->capacity == 0 ? 4 : 2 * (pst->capacity);
STDataType* tmp = (STDataType*)realloc(pst->a, newcapacity * sizeof(STDataType));;
if (tmp == NULL)
{
perror(malloc);
}
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;
}
// 获取数据个数
int STSize(ST* pst)
{
assert(pst);
return pst->top;
}
bool isValid(char* s) {
ST st;
STInit(&st);
while(*s)
{
//左括号入栈
if(*s=='(' || *s=='[' || *s=='{')
{
STPush(&st,*s);
}
else
{
if(STEmpty(&st))
{
STDestroy(&st);
return false;
}
//取栈顶与右括号匹配
char top=STTop(&st);
STPop(&st);
if((top=='(' && *s!=')')
|| (top=='[' && *s!=']')
|| (top=='{' && *s!='}'))
{
STDestroy(&st);
return false;
}
}
++s;
}
bool ret=STEmpty(&st);
STDestroy(&st);
return ret;
}
我们需要判断一对括号是否匹配,匹配的话就返回turn,失败就返回false。我们用栈来实现这个,栈是先进后出的,如果是左括号就入栈,如果是右括号就让栈里的左括号与右括号进行匹配,如果匹配上就继续匹配下一个。这里有特殊情况,如果刚开始入栈的是右括号肯定不匹配,直接返回false。还有一种情况,就是遍历完一遍后还有左括号,这时就要判断一下栈是否为空了。
注意:用c语言来实现要添加实现栈的代码。