当前位置:网站首页>【LeetCode】20.有效的括号
【LeetCode】20.有效的括号
2022-08-02 02:40:00 【酥酥~】
题目
给定一个只包括 ‘(’,‘)’,‘{’,‘}’,‘[’,‘]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
示例 1:
输入:s = “()”
输出:true
示例 2:
输入:s = “()[]{}”
输出:true
示例 3:
输入:s = “(]”
输出:false
示例 4:
输入:s = “([)]”
输出:false
示例 5:
输入:s = “{[]}”
输出:true
提示:
1 <= s.length <= 104
s 仅由括号 ‘()[]{}’ 组成
题解
使用栈来进行
使用map存储括号对
class Solution {
public:
bool isValid(string s) {
int len = s.length();
if(len%2==1)
return false;
unordered_map<char,char> pairs={
{
')','('},
{
']','['},
{
'}','{'}};
stack<char> mystack;
for(char ch:s)
{
if(pairs.count(ch))
{
if(mystack.empty() || mystack.top() != pairs[ch])
{
return false;
}
mystack.pop();
}
else
{
mystack.push(ch);
}
}
return mystack.empty();
}
};
边栏推荐
猜你喜欢

NAS和私有云盘的区别?1篇文章说清楚

因为WiFi原因navicat 无法连接数据库Mysql

Entry name 'org/apache/commons/codec/language/bm/gen_approx_greeklatin.txt' collided

Chopper webshell feature analysis

ofstream,ifstream,fstream read and write files

analog IC layout-Design for reliability

Nacos源码分析专题(二)-服务注册

【web】Understanding Cookie and Session Mechanism

Nanoprobes多组氨酸 (His-) 标签标记:重组蛋白检测方案

网络层解析——IP协议、地址管理、路由选择
随机推荐
Chapter 7 Noise analysis
MySQL - CRUD operations
AWR analysis report questions for help: How can SQL be optimized from what aspects?
Nanoprobes免疫测定丨FluoroNanogold试剂免疫染色方案
AcWing 1285. 单词 题解(AC自动机)
Remember a pit for gorm initialization
Nanoprobes丨1-mercapto-(triethylene glycol) methyl ether functionalized gold nanoparticles
BI-SQL丨WHILE
指针数组和数组指针
永磁同步电机36问(二)——机械量与电物理量如何转化?
微信小程序异步回调函数恶梦和解决办法
789. 数的范围
The first time I wrote a programming interview question for Niu Ke: input a string and return the letter with the most occurrences of the string
2022-07-30 mysql8 executes slow SQL-Q17 analysis
最大层内元素和
Swift运行时(派发机制)
欧拉公式的证明
数仓:数仓从ETL到ELT架构的转化以及俩者的区别
790. 数的三次方根
Nacos源码分析专题(二)-服务注册