当前位置:网站首页>栈的应用——力扣 20.有效的括号
栈的应用——力扣 20.有效的括号
2022-08-05 05:16:00 【ZJNUCoconut】
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
示例 1:
输入:s = "()"
输出:true
示例 2:
输入:s = "()[]{}"
输出:true
示例 3:
输入:s = "(]"
输出:false
示例 4:
输入:s = "([)]"
输出:false
示例 5:
输入:s = "{[]}"
输出:true
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。方法一:栈
判断括号的有效性可以使用「栈」这一数据结构来解决。
我们遍历给定的字符串 s。当我们遇到一个左括号时,我们会期望在后续的遍历中,有一个相同类型的右括号将其闭合。由于后遇到的左括号要先闭合,因此我们可以将这个左括号放入栈顶。
当我们遇到一个右括号时,我们需要将一个相同类型的左括号闭合。此时,我们可以取出栈顶的左括号并判断它们是否是相同类型的括号。如果不是相同的类型,或者栈中并没有左括号,那么字符串 s 无效,返回 False。为了快速判断括号的类型,我们可以使用哈希表存储每一种括号。哈希表的键为右括号,值为相同类型的左括。
在遍历结束后,如果栈中没有左括号,说明我们将字符串 s 中的所有左括号闭合,返回 True,否则返回 False。
注意到有效字符串的长度一定为偶数,因此如果字符串的长度为奇数,我们可以直接返回 False,省去后续的遍历判断过程
C语言官方答案
char pairs(char a) {
if (a == '}') return '{';
if (a == ']') return '[';
if (a == ')') return '(';
return 0;
}
bool isValid(char* s) {
int n = strlen(s);
if (n % 2 == 1) {
return false;
}
int stk[n + 1], top = 0;
for (int i = 0; i < n; i++) {
char ch = pairs(s[i]);
if (ch) {
if (top == 0 || stk[top - 1] != ch) {
return false;
}
top--;
} else {
stk[top++] = s[i];
}
}
return top == 0;
}
Java
class Solution {
public boolean isValid(String s) {
int n = s.length();
if (n % 2 == 1) {
return false;
}
Map<Character, Character> pairs = new HashMap<Character, Character>() {
{
put(')', '(');
put(']', '[');
put('}', '{');
}};
Deque<Character> stack = new LinkedList<Character>();
for (int i = 0; i < n; i++) {
char ch = s.charAt(i);
if (pairs.containsKey(ch)) {
if (stack.isEmpty() || stack.peek() != pairs.get(ch)) {
return false;
}
stack.pop();
} else {
stack.push(ch);
}
}
return stack.isEmpty();
}
}
边栏推荐
猜你喜欢

五、请求处理—Rest映射是怎样实现的?

【Multisim仿真】直流稳压电源设计报告

华科提出首个用于伪装实例分割的一阶段框架OSFormer

IT系统运行维护方法及策略
![[Database and SQL study notes] 9. (T-SQL language) Define variables, advanced queries, process control (conditions, loops, etc.)](/img/7e/566bfa17c5b138d1f909185721c735.png)
[Database and SQL study notes] 9. (T-SQL language) Define variables, advanced queries, process control (conditions, loops, etc.)

Thread handler handle IntentServvice handlerThread
![[Pytorch study notes] 9. How to evaluate the classification results of the classifier - using confusion matrix, F1-score, ROC curve, PR curve, etc. (taking Softmax binary classification as an example)](/img/ac/884d8aba8b9d363e3b9ae6de33d5a4.png)
[Pytorch study notes] 9. How to evaluate the classification results of the classifier - using confusion matrix, F1-score, ROC curve, PR curve, etc. (taking Softmax binary classification as an example)

【Pytorch学习笔记】10.如何快速创建一个自己的Dataset数据集对象(继承Dataset类并重写对应方法)
![[Database and SQL study notes] 10. (T-SQL language) functions, stored procedures, triggers](/img/b9/06b90160c962a25a3cc44731afb6dc.png)
[Database and SQL study notes] 10. (T-SQL language) functions, stored procedures, triggers

基于STM32F407的WIFI通信(使用的是ESP8266模块)
随机推荐
面向小白的深度学习代码库,一行代码实现30+中attention机制。
单变量线性回归
一个小时教你如何掌握ts基础
Service
[Kaggle project actual combat record] Steps and ideas sharing of a picture classification project - taking leaf classification as an example (using Pytorch)
多边形等分
OSPF故障排除办法
Jupyter notebook选择不同的Anaconda环境作为内核运行
读论文 - Unpaired Portrait Drawing Generation via Asymmetric Cycle Mapping
Redis设计与实现(第一部分):数据结构与对象
AIDL detailed explanation
【Pytorch学习笔记】8.训练类别不均衡数据时,如何使用WeightedRandomSampler(权重采样器)
MSRA proposes extreme masking model ExtreMA for learning instances and distributed visual representations
ECCV2022 | RU & Google propose zero-shot object detection with CLIP!
LeetCode刷题之第129题
LeetCode刷题之第33题
关于使用QML的MediaPlayer实现视频和音频的播放时遇到的一些坑
MaskDistill - Semantic segmentation without labeled data
CAN、CAN FD
dataframe 常用操作