题目分析:
给定的字符串s可能为空串,空串返回false,不为空串时进行以下操作遍历字符串,左括号 '(' 、 '[' 、 '{' 压栈,右括号与此时的栈顶元素对比匹配
1️⃣匹配,则栈顶元素出栈,继续遍历字符串
2️⃣不匹配:分为空栈和非空栈两种情况
- 空栈:则数量不匹配,返回false
- 非空栈:右括号与栈顶元素不匹配,返回false
以上情况没有返回,即字符串遍历结束没有返回,此时需要判断栈的情况,栈空则所有右括号匹配成功,返回true;栈非空则说明有左括号未匹配成功,返回false
📖Note:
C语言中没有栈,我们需要自己进行栈及栈的相关操作的定义
以下为参考代码:
#define SDataType char
//定义栈
typedef struct stack
{SDataType* a;int top;int capacity;
}ST;
//初始化
void StackInit(ST* ps)
{assert(ps);ps->a = NULL;ps->top = ps->capacity = 0;
}//销毁
void StackDestroy(ST* ps)
{assert(ps);free(ps->a);ps->a = NULL;ps->top = ps->capacity = 0;
}
//压栈
void StackPush(ST* ps, SDataType x)
{assert(ps);//扩容if (ps->top == ps->capacity){int newcapacity = ps->capacity == 0 ? 4 : (ps->capacity) * 2;SDataType* tmp = realloc(ps->a, newcapacity * sizeof(SDataType));//扩容失败if (tmp == NULL){perror("realloc fail");exit(-1);}//扩容成功ps->a = tmp;ps->capacity = newcapacity;}//插入数据ps->a[ps->top] = x;ps->top++;
}
//判断栈空
bool StackEmpty(ST* ps)
{assert(ps);return ps->top == 0;
}
//出栈
void StackPop(ST* ps)
{assert(ps);if(!StackEmpty(ps)){ps->top--;}
}//访问栈顶元素
SDataType StackTop(ST* ps)
{assert(ps);if(!StackEmpty(ps)){return ps->a[ps->top-1];}return -1;}bool isValid(char * s){ST st;StackInit(&st);while(*s){//左括号压栈if(*s == '(' || *s == '[' || *s == '{'){StackPush(&st, *s);}//右括号则与栈顶元素比较是否匹配else{//空栈:括号数量不匹配if(!StackEmpty){StackDestroy(&st);return false;}//非空栈char ch = StackTop(&st);StackPop(&st);if(*s == '}' && ch != '{' || *s == ']' && ch != '[' || *s == ')' && ch != '('){StackDestroy(&st);return false;}}++s;}//此时栈不为空,则数量不匹配,即有左括号未匹配;栈为空即所有括号匹配成功bool flag = StackEmpty(&st);StackDestroy(&st);return flag;;}