一、题目链接:. - 力扣(LeetCode)


二、代码
typedef char STDataType;
typedef struct Stack
{
STDataType* a;
int top; // 栈顶
int capacity; // 容量
}Stack;
// 初始化栈
void StackInit(Stack* ps);
// 入栈
void StackPush(Stack* ps, STDataType data);
// 出栈
void StackPop(Stack* ps);
// 获取栈顶元素
STDataType StackTop(Stack* ps);
// 检测栈是否为空,如果为空返回非零结果,如果不为空返回0
int StackEmpty(Stack* ps);
// 初始化栈
void StackInit(Stack* ps)
{
assert(ps);
ps->a = NULL;
ps->capacity =0;
ps->top =0;
}
// 入栈
void StackPush(Stack* ps, STDataType data)
{
assert(ps);
if (ps->capacity == ps->top)
{
int newcapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
STDataType* p = (STDataType*)realloc(ps->a, sizeof(STDataType) * newcapacity);
if (p == NULL)
{
perror("realloc fail");
return;
}
ps->a = p;
ps->capacity = newcapacity;
}
ps->a[ps->top] = data;
ps->top++;
}
// 出栈
void StackPop(Stack* ps)
{
assert(ps);
int ret= StackEmpty(ps);
if (ret != 0)
{
printf("栈为空\n");
return;
}
ps->top--;
}
// 获取栈顶元素
STDataType StackTop(Stack* ps)
{
assert(ps);
int ret = StackEmpty(ps);
if (ret != 0)
{
printf("栈为空\n");
return -1;
}
int n = ps->top-1;
return ps->a[n];
}
// 检测栈是否为空,如果为空返回非零结果,如果不为空返回0
int StackEmpty(Stack* ps)
{
assert(ps);
return ps->top == 0;//top是0,就会返回1.不是0,就会返回0
}
Stack sta;
bool isValid(char* s) {
StackInit(&sta);//初始化
while(*s)
{
if(*s=='('||*s=='{'||*s=='[')//读入左括号
StackPush(&sta,*s);//左括号入栈
else
{
if(StackEmpty(&sta))
return false;
char temp=StackTop(&sta);//取栈顶元素
StackPop(&sta); //出栈,更新栈顶元素
if(
(temp=='('&&*s!=')')||
(temp=='['&&*s!=']')||
(temp=='{'&&*s!='}')
) //如果栈顶元素无法与之匹配,就说明失败了
return false;
}
s++;//让字符指针向后移动
}
if(StackEmpty(&sta))//如果最后栈为空,就说明成功
return true;
else
return false;
}
三、方法解释
1.创建一个顺序栈
2.判断字符串当前字符是否为左括号,是的话就入栈
3.如果字符串的当前字符是右括号,就需要去此时的栈顶元素,进行匹配
4.如果匹配失败就直接返回false
5.如果无左括号入栈,栈中也就无元素,就直接返回false
6.循环结束后,最后判断栈是否为空,为空说明成功,返回true,反之就是false
628

被折叠的 条评论
为什么被折叠?



