当前位置:网站首页>LeetCode每日一练 —— 20. 有效的括号
LeetCode每日一练 —— 20. 有效的括号
2022-08-02 10:31:00 【飞向星的客机】
前言
Wassup guys!我是Edison
今天是 LeetCode 上的 leetcode 20. 有效的括号
Let’s get it!

1. 题目描述
给定一个只包括
'(',')','{','}','[',']'的字符串 s ,判断字符串是否有效。
有效字符串需满足:
1、左括号必须用相同类型的右括号闭合。
2、左括号必须以正确的顺序闭合。
示例 1:
输入:s = "()"
输出:true
示例 2:
输入:s = "()[]{}"
输出:true
示例 3:
输入:s = "(]"
输出:false
示例 4:
输入:s = "([)]"
输出:false
示例 5:
输入:s = "{[]}"
输出:true
2. 思路分析
栈 是一种 先进后出 的数据结构,处理括号问题的时候尤其有用。
思路:
(1)遇到左括号,就入栈
(2)遇到右括号,就去栈中寻找最近的左括号,看是否匹配,然后出栈
步骤:
遍历字符串,遇到前括号直接入栈。
遇到后括号,判断该后括号与栈顶的前括号是否匹配(若此时栈为空,则字符串无效),若不匹配则字符串无效;
若匹配则删除栈顶元素,继续遍历字符串,直到字符串遍历完毕。
当字符串遍历完后,检测栈是否为空,若为空,则字符串有效,若不为空,说明有前括号未匹配,字符串无效。
3. 代码实现
这道题如果用 C 实现的话,就需要我们自己去写一个栈;
而如果用 C++ 实现的话,直接用 STL 即可;
接口代码
typedef char STDataType;
// 支持动态增长的栈
typedef struct Stack
{
STDataType* a;
int top; //栈顶
int capacity; //容量
}ST;
//初始化栈
void StackInit(ST* ps);
//入栈
void StackPush(ST* ps, STDataType x);
//出栈
void StackPop(ST* ps);
//获取栈顶元素
STDataType StackTop(ST* ps);
// 获取栈中有效元素个数
int StackSize(ST* ps);
//检测栈是否为空,如果为空返回非零结果,如果不为空返回0
bool StackEmpty(ST* ps);
//销毁栈
void StackDestroy(ST* ps);
//————————————————————————————————————————————————————————————————
//初始化栈
void StackInit(ST* ps) {
assert(ps);
ps->a = NULL;
ps->top = 0;
ps->capacity = 0;
}
//入栈
void StackPush(ST* ps, STDataType x) {
assert(ps);
//满了扩容
if (ps->top == ps->capacity) {
int newCapacity = ps->capacity == (0) ? (4) : (ps->capacity * 2);
ps->a = realloc(ps->a, newCapacity * sizeof(STDataType));
if (ps->a == NULL) {
printf("realloc fail\n");
exit(-1);
}
ps->capacity = newCapacity;
}
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];
}
// 获取栈中有效元素个数
int StackSize(ST* ps) {
assert(ps);
return ps->top;
}
//检测栈是否为空,如果为空返回非零结果,如果不为空返回0
bool StackEmpty(ST* ps) {
assert(ps);
//如果top等于0,就是空
return ps->top == 0;
}
//销毁栈
void StackDestroy(ST* ps) {
assert(ps);
free(ps->a);
ps->a = NULL;
ps->capacity = ps->top = 0;
}
//————————————————————————————————————————————————————————————————
bool isValid(char * s){
ST st; //先定义一个栈
StackInit(&st);
while (*s)
{
//如果是左括号,就入栈
if (*s == '[' || *s == '(' || *s == '{') {
StackPush(&st, *s); //把左括号放入栈里面
++s;
}
else {
//出栈
/*假设只输入了一个']',那么就会进行出栈判断; 因为输入的是右括号,直接到这里进行判断,那么栈肯定为空,所以直接return false */
if (StackEmpty(&st)) {
return false;
}
char top = StackTop(&st); //把栈顶的左括号拿出来,放到top中
StackPop(&st);
if (*s == ']' && top != '[') {
StackDestroy(&st);
return false;
}
else if (*s == ')' && top != '(') {
StackDestroy(&st);
return false;
}
else if (*s == '}' && top != '{') {
StackDestroy(&st);
return false;
}
else {
//说明匹配了
++s; //匹配,继续比
}
}
}
//栈为空,说明所以左括号都匹配了
//栈不为空,就false,栈为空,就是true
bool ret = StackEmpty(&st);
StackDestroy(&st); //销毁栈
return ret;
}
提交结果
边栏推荐
- LayaBox---TypeScript---Module
- The 38-year-old daughter is not in love and has no stable job, the old mother is crying
- 【术语科普】关于集成工作台那些难懂的词儿,看这篇秒懂!
- 详细总结SoC、DSP、MCU、GPU和FPGA等基础概念
- 周杰伦新歌发布,爬取《Mojito》MV弹幕,看看粉丝们都说的些啥!
- 转转反爬攻防战
- 神通数据库,批量插入数据的时候失败
- R语言ggplot2可视化:使用ggpubr包的ggbarplot函数可视化水平柱状图(条形图)、使用orientation参数设置柱状图转置为条形图
- R语言ggplot2可视化:基于aes函数中的fill参数和shape参数自定义绘制分组折线图并添加数据点(散点)、使用theme函数的legend.position函数配置图例到图像右侧
- Verilog的随机数系统任务----$random
猜你喜欢

List-based queuing and calling system

MSYS2 QtCreator Clangd code analysis can not find mm_malloc.h problem remedy

你好,我的新名字叫“铜锁/Tongsuo”

Do you agree with this view?Most businesses are digitizing just to ease anxiety

超赞!发现一个APP逆向神器!

The heavyweights are coming!Spoilers for the highlights of the Alibaba Cloud Life Science and Intelligent Computing Summit

npm ERR! 400 Bad Request - PUT xxx - Cannot publish over previously published version “1.0.0“.

iNFTnews | Seeing the two sides of the metaverse, what is the true Internet and the Internet of value?

MSYS2 QtCreator Clangd 代码分析找不到 mm_malloc.h的问题补救

npm ERR! 400 Bad Request - PUT xxx - Cannot publish over previously published version “1.0.0“.
随机推荐
情景剧《重走长征路》上演
Turning and anti-climbing attack and defense
R语言时间序列数据算术运算:使用log函数将时间序列数据的数值对数化、使用diff函数计算对数化后的时间序列数据的逐次差分(计算价格的对数差分)
currentstyle 织梦_dede currentstyle属性完美解决方案
LayaBox---TypeScript---Namespaces and modules
After 21 years of graduation, I switched to software testing. From 0 income to a monthly salary of over 10,000, I am really lucky...
Jay Chou's new song is released, crawl the "Mojito" MV barrage, and see what the fans have to say!
鸿星尔克再捐一个亿
一款优秀的中文识别库——ocr
Long battery life or safer?Seal and dark blue SL03 comparison shopping guide
LayaBox---TypeScript---迭代器和生成器
3 d laser slam: LeGO - LOAM - ground point extracting method and the analysis of the code
LayaBox---TypeScript---声明合并
周杰伦新歌发布,爬取《Mojito》MV弹幕,看看粉丝们都说的些啥!
牛客刷题——剑指offer(第三期)
Why use BGP?
LayaBox---TypeScript---三斜线指令
多大数量级会出现哈希碰撞
DVWA Clearance Log 2 - Command Injection
The ggline function of the R language ggpubr package visualizes grouped line graphs, the add parameter is mean_se and dotplot to visualize line graphs of different level averages, and adds error bars