【初阶数据结构题目】15.有效的括号

有效的括号

点击链接答题

思路:

定义一个指针ps遍历字符串

ps遍历到的字符为左括号,入栈

ps遍历到的字符为右括号,取栈顶元素与ps进行比较,

  1. 栈顶元素 匹配 *ps,出栈,ps++
  2. 栈顶元素 不匹配 *ps,返回false

代码:

//定义栈的结构
typedef char STDataType;
typedef struct Stack {
	STDataType* arr;
	int capacity;//栈的空间大小
	int top;//栈顶
}ST;

//栈的初始化
void STInit(ST* ps) {
	assert(ps);
	ps->arr = NULL;
	ps->capacity = ps->top = 0;
}

//栈的销毁
void STDestory(ST* ps) {
	assert(ps);
	if (ps->arr) {
		free(ps->arr);
	}
	ps->arr = NULL;
	ps->top = ps->capacity = 0;
}

//栈顶---入数据,出数据
//入数据
void StackPush(ST* ps, STDataType x) {
	assert(ps);
	//1.判断空间是否足够
	if (ps->capacity == ps->top) {
		int newCapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;//增容
		STDataType* tmp = (STDataType*)realloc(ps->arr, newCapacity * sizeof(STDataType));
		if (tmp == NULL) {
			perror("relloc fail!");
			exit(1);
		}
		ps->arr = tmp;
		ps->capacity = newCapacity;
	}
	//空间足够
	ps->arr[ps->top++] = x;
}

//判断栈是否为空
bool StackEmpty(ST* ps) {
	assert(ps);
	return ps->top == 0;
}

//出数据
void StackPop(ST* ps) {
	assert(ps);
	assert(!StackEmpty(ps));//栈为空报错
	--ps->top;
}

//获取栈中有效元素个数
int STSize(ST* ps){
	assert(ps);
	return ps->top;
}

//取栈顶元素
STDataType StackTop(ST* ps) {
	assert(ps);
	assert(!StackEmpty(ps));

	return ps->arr[ps->top - 1];
}

bool isValid(char* s) {
    ST st;
    //初始化
    STInit(&st);
    //遍历字符串s
    char* ps = s;
    while(*ps != '\0'){
        //左括号,入栈
        if(*ps == '(' || *ps == '[' || *ps == '{'){
            StackPush(&st, *ps);
        }
        else{//右括号,和栈顶元素比较是否匹配
        //栈为空,直接返回false
        if(StackEmpty(&st)){
            return false;
        }
        //栈不为空才能取栈顶元素
            char ch = StackTop(&st);
            if((*ps == ')' && ch == '(')
            || (*ps == ']' && ch == '[')
            || (*ps == '}' && ch == '{') ){
                StackPop(&st);
            } 
            else{
                //不匹配
                STDestory(&st);
                return false;
            }
        }
        ps++;

    }
    bool ret = StackEmpty(&st) == true;//如果为空,返回true
    //销毁
    STDestory(&st);
    return ret;
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值