当前位置:网站首页>20.有效的括号
20.有效的括号
2022-07-23 04:32:00 【rananie】
20.有效的括号
题目
给定一个只包括 ‘(’,‘)’,‘{’,‘}’,‘[’,‘]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
示例 1:
输入:s = "()"
输出:true
示例 2:
输入:s = "()[]{}"
输出:true
示例 3:
输入:s = "(]"
输出:false
示例 4:
输入:s = "([)]"
输出:false
示例 5:
输入:s = "{[]}"
输出:true
提示:
- 1 <= s.length <= 104
- s 仅由括号 ‘()[]{}’ 组成
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/valid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解
思路
括号匹配可以使用栈实现。
- 遇见
({[左括号就把对应的)}]右括号入栈。 - 遇见右括号就和栈里的右括号进行比较,不相等说明没有匹配上,返回false
- 字符串遍历完毕后,栈为空则返回true
function isValid(s: string): boolean {
let len = s.length;
if(len==1)return false;
let stack = new Array();
for(let char of s){
if(char == '(') stack.push(')');
else if(char == '[') stack.push(']');
else if(char == '{') stack.push('}');
else if(char == ')' && stack.pop()!=')')return false;
else if(char == ']' && stack.pop()!=']')return false;
else if(char == '}' && stack.pop()!='}')return false;
}
return stack.length==0;
};
边栏推荐
- Unity Image中Sprite和overrideSprite区别(转载)
- 阿里云如何将一个域名解析到另一个域名上
- 32.< tag-数组和位运算>补充: lt.剑指 Offer 56 - I. 数组中数字出现的次数
- Chapter 4: runtime data area - shared space
- 低代码平台搭建医药企业供应商、医院、患者等多方协同管理案例分析
- Chapter 3 Standard Input
- 第四篇章:运行时数据区——共享空间
- 8.< tag-动态规划和LCS问题>lt.300. 最长递增子序列 + lt.674. 最长连续递增序列
- 【Warning】YOLOV5训练时的ignoring corrupt image/label: [Errno 2].....,无法全部训练数据集,快速带你解决它
- 比你老师详细系列————结构体
猜你喜欢

序列模型(三)- 序列模型和注意力机制

C# IValueConverter接口用法举例
![[Delphi] a simple method to make the installation icon of the control panel (translation)](/img/e9/2a9c509e4ebbd4ff0a32be547e1cbb.png)
[Delphi] a simple method to make the installation icon of the control panel (translation)

Seektiger's okaleido has a big move. Will the STI of ecological pass break out?

New file / filter / folder in VS

chrome selenium 用默认profile 不必每次清空

The safe distance between you and personal information leakage may be decided by a laptop!

推荐一款 Shell 装逼神器,已开源!网友:真香。。。

Self operation and maintenance: a new sample of it operation and maintenance services in Colleges and Universities

How to delete an item in sonar
随机推荐
【Warning】YOLOV5训练时的ignoring corrupt image/label: [Errno 2].....,无法全部训练数据集,快速带你解决它
数据湖:从数据仓库看数据湖
为什么我们无法写出真正可重用的C#/F#代码?
网络安全等级保护2.0标准解析
云徙科技CTO李楠:技术和技术人,与数字化共同进化
SQLZOO——SELECT Quiz
Interest rate in installment payment
MapReduce进阶
SQLZOO——SELECT from WORLD Tutorial
toco生成tflite模型
Redis pseudo cluster one click deployment script - pro test available
PXE远程安装和Kickstart无人值守安装 技术文档
Exciting metauniverse! Wealth outlet of next generation Internet
TZC 1283: 简单排序 —— 堆排序
12 个适合做外包项目的开源后台管理系统
什么是即时通讯?即时通讯的发展
【Qt5.12】Qt5.12安装教程
8.< tag-动态规划和LCS问题>lt.300. 最长递增子序列 + lt.674. 最长连续递增序列
[warning] recognizing corrupt image/label during yolov5 training: [errno 2]...... it is impossible to complete the training data set. I will take you to solve it quickly
LeetCode刷题--点滴记录023