当前位置: 首页 > news >正文

【有效的括号】

题目

1、左括号入栈
2、右括号出栈顶括号进行匹配

typedef char STDataType;
//元素为char类型
typedef struct Stack
{STDataType* a;//动态的开辟空间int top;int capacity;
}ST;void StackInit(ST* ps)//初始化
{assert(ps);ps->a = (STDataType*)malloc(sizeof(STDataType) * 4);if (ps->a == NULL){printf("malloc fail\n");exit(-1);}ps->capacity = 4;ps->top = 0;//top一开始指向0位置(也可以指向-1位置)
}void StackDestory(ST* ps)//销毁
{assert(ps);free(ps->a);ps->a = NULL;ps->top = ps->capacity = 0;
}int StackSize(ST* ps)//元素个数
{assert(ps);return ps->top;//top从0开始
}void StackPush(ST* ps, STDataType x)//入栈
{assert(ps);//空间不够用 开辟空间if (ps->top == ps->capacity){STDataType* tmp = (STDataType*)realloc(ps->a, ps->capacity * 2 * sizeof(STDataType));if (tmp == NULL){printf("realloc fail\n");exit(-1);}else{ps->a = tmp;ps->capacity *= 2;}}ps->a[ps->top] = x;ps->top++;
}void StackPop(ST* ps)//出栈
{assert(ps);assert(ps->top > 0);ps->top--;
}STDataType StackTop(ST* ps)//取栈顶元素
{assert(ps);assert(ps->top > 0);return ps->a[ps->top - 1];
}bool StackEmpty(ST* ps)//判断是否为空
{assert(ps);return ps->top == 0;
}

题目求解

bool isValid(char * s){ST st;StackInit(&st);//字符串没有走到结束条件while((*s)!='\0'){if((*s) == '('||(*s) == '['||(*s) == '{'){StackPush(&st,*s);}else{if(StackEmpty(&st)){StackDestory(&st);//内存泄漏return false;}char top = StackTop(&st);StackPop(&st);if((*s == ')'&&top !='(')||(*s == ']'&&top !='[')||(*s == '}'&&top !='{')){StackDestory(&st);return false;}}s++;}bool ret = StackEmpty(&st);StackDestory(&st);return ret;
}
http://www.lryc.cn/news/140372.html

相关文章:

  • 积跬步至千里 || 数学基础、算法与编程
  • Java单元测试 JUnit 5 快速上手
  • 【Linux网络】TCP UDP socket HTTP webSocket之间的区别
  • 【面向大一新生IT技术社群招新啦,不来瞅瞅?】
  • 分析系统 - 使用Python爬虫
  • strstr函数
  • [C++] string类常用接口的模拟实现
  • 每日一学——防火墙
  • 常用数据库备份方法,sql数据库备份方法
  • 常见前端面试之VUE面试题汇总八
  • 弯道超车必做好题集锦二(C语言选择题)
  • PROFIBUS主站转MODBUS TCP网关
  • 【力扣】盛最多水的容器
  • 【SQL应知应会】索引(三)• MySQL版:聚簇索引与非聚簇索引;查看索引与删除索引;索引方法
  • rtmp直播
  • 4.14 tcp_tw_reuse 为什么默认是关闭的?
  • Python数据分析和爬虫:解析数据的强大工具
  • 机器学习之SGD(Stochastic Gradient Descent,随机梯度下降)
  • leetcode做题笔记100. 相同的树
  • 【Hadoop】Hadoop入门概念简介
  • 前端监控之异常监控(一)
  • sql server 、mysql CTE 公用表表达式
  • Oracle dataguard 和Oracle rac的区别和联系
  • JUC工具类-LockSupport概述
  • 大数据:AI大模型对数据分析领域的颠覆(文末送书)
  • CEdit 选中文字实时更新到另一个控件中
  • Word导出创建Adobe PDF其中emf图片公式马赛克化及文字缺失
  • [matlab]matlab配置mingw64编译器
  • 华为OD-非严格递增连续数字序列
  • css滚动条样式这样修改下很漂亮