当前位置:网站首页>栈的应用——力扣 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();
}
}
边栏推荐
- You should write like this
- 发顶会顶刊论文,你应该这样写作
- 【论文精读】Rich Feature Hierarchies for Accurate Object Detection and Semantic Segmentation(R-CNN)
- MSRA proposes extreme masking model ExtreMA for learning instances and distributed visual representations
- 5G中切片网络的核心技术FlexE
- 对象比较
- [Database and SQL study notes] 9. (T-SQL language) Define variables, advanced queries, process control (conditions, loops, etc.)
- 读论文 - Unpaired Portrait Drawing Generation via Asymmetric Cycle Mapping
- 【ts】typescript高阶:typeof使用
- PID详解
猜你喜欢

【ts】typescript高阶:模版字面量类型

【shell编程】第二章:条件测试语句

Detailed explanation of BroadCast Receiver (broadcast)

二、自动配置之底层注解

PID详解

【Shell编程】第一章:子串
![[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学习笔记】9.分类器的分类结果如何评估——使用混淆矩阵、F1-score、ROC曲线、PR曲线等(以Softmax二分类为例)

【数据库和SQL学习笔记】6.SELECT查询4:嵌套查询、对查询结果进行操作
随机推荐
【Promise高级用法】实现并行和串行API
[Database and SQL study notes] 9. (T-SQL language) Define variables, advanced queries, process control (conditions, loops, etc.)
八、响应处理——ReturnValueHandler匹配返回值处理器并处理返回值原理解析
Service
【ts】typescript高阶:映射类型与keyof
CVPR最佳论文得主清华黄高团队提出首篇动态网络综述
LeetCode刷题之第746题
伪RTOS-ProroThread在CH573芯片上的移植
CAN、CAN FD
5G中切片网络的核心技术FlexE
【Pytorch学习笔记】8.训练类别不均衡数据时,如何使用WeightedRandomSampler(权重采样器)
A deep learning code base for Xiaobai, one line of code implements 30+ attention mechanisms.
【nodejs】第一章:nodejs架构
数控直流电源
【Pytorch学习笔记】11.取Dataset的子集、给Dataset打乱顺序的方法(使用Subset、random_split)
九、响应处理——内容协商底层原理
Thread handler handle IntentServvice handlerThread
OSPF故障排除办法
八、请求处理之自定义类型参数绑定原理
Redis集群(docker版)——从原理到实战超详细