当前位置:网站首页>20. 有效的括号
20. 有效的括号
2022-06-11 08:55:00 【拽拽就是我】
leetcode力扣刷题打卡
题目:20. 有效的括号
描述:给定一个只包括 ‘(’,‘)’,‘{’,‘}’,‘[’,‘]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
解题思路
1、遇见括号问题,基本就是栈解决;
2、栈为空,直接push进来;栈不为空,就比较栈顶元素和新元素是否配对,配对就直接出栈;
3、最后判断栈是否为空,全部都配对了栈肯定为空,返回true,反之返回false;
原代码##
class Solution {
public:
bool ispair(char a, char b) {
switch (a) {
case '(':
if (b == ')') return true;
else return false;
case '{':
if (b == '}') return true;
else return false;
case '[':
if (b == ']') return true;
else return false;
default:
return false;
}
}
bool isValid(string s) {
stack<char>sc;
for (int i = 0; i < s.size(); ++i) {
if (sc.empty()) {
sc.push(s[i]);
continue;
} else {
char temp = sc.top();
if (ispair(temp, s[i])) sc.pop();
else sc.push(s[i]);
}
}
if (sc.empty()) return true;
else return false;
}
};
边栏推荐
- 九九乘法表
- leetcode - 460. LFU 缓存
- 剑指 Offer 62. 圆圈中最后剩下的数字
- K8S应用(四)—— 搭建redis5 集群(可供外部直接访问)
- 硅树脂油漆申请美国标准UL 790 Class A 合适吗?
- 深度学习入门之pytorch安装
- Mazhiqiang: research progress and application of speech recognition technology -- RTC dev Meetup
- String类为何final修饰
- Implementation of CRF for named entity recognition
- K8s application (IV) - build a redis5 cluster (for direct external access)
猜你喜欢

Getting started with Zipkin

What if the copied code format is confused?

Sword finger offer 10- ii Frog jumping on steps

(一)aac开篇-核心组件原理之Lifecycle、LiveData、ViewModel与源码分析技巧(转载)

剑指 Offer 21. 调整数组顺序使奇数位于偶数前面

ActiveMQ simple tutorial, suitable for beginners, learning notes yyds

补2:圆环回原点问题

SAP ODATA 开发教程

leetcode - 518. Change II

Android 面试笔录(精心整理篇)
随机推荐
K8s application (IV) - build a redis5 cluster (for direct external access)
[Clickhouse column] user initialization of new library role
[cvpr2022] intensive reading of querydet papers
SAP abap 字段符号
GCC AVR (ATMEL studio+ AVR studio) how to define the structure array in the program memory (flash) space and read it
【node】npm部分
En45545-2 R26 vertical combustion test introduction
欧洲家具EN 597-1 跟EN 597-2两个阻燃标准一样吗?
知识图谱入门之---yedda标注
leveldb简单使用样例
Using docker compose to build redis5 cluster
完整的ES6面试题
GCC AVR(Atmel Studio+ AVR Studio)如何将结构体数组定义在程序存储器(flash)空间并进行读操作
Classical graph theory, depth first and breadth first, topology, prim and krukal, it's time to review
马志强:语音识别技术研究进展和应用落地分享丨RTC Dev Meetup
For in / for of / foreach loop
php 上传大文件 超过40秒 服务器500
(一)aac开篇-核心组件原理之Lifecycle、LiveData、ViewModel与源码分析技巧(转载)
光伏板怎么申请ASTM E108阻燃测试?
E. X的放大与缩小(运算符重载)