当前位置:网站首页>leetcode 20. Valid Parentheses 有效的括号(中等)
leetcode 20. Valid Parentheses 有效的括号(中等)
2022-08-09 12:26:00 【InfoQ】
一、题目大意
- 1 <= s.length <= 104
- s 仅由括号 '()[]{}' 组成
二、解题思路
三、解题方法
3.1 Java实现
public class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (Character c : s.toCharArray()) {
if (isPush(stack, c)) {
stack.push(c);
} else {
stack.pop();
}
}
return stack.isEmpty();
}
private boolean isPush(Stack<Character> stack, Character c) {
if (stack.isEmpty()) {
return true;
}
// {[(
boolean isPop = (stack.peek().equals('[') && c.equals(']') ||
stack.peek().equals('{') && c.equals('}') ||
stack.peek().equals('(') && c.equals(')'));
return !isPop;
}
}
3.2 2014年的实现
public class Solution {
public boolean isValid(String s) {
if (s == null || s.length() == 0) {
return true;
}
Stack<Byte> ps = new Stack<Byte>();
byte[] bArr = s.getBytes();
boolean isValid = true;
for (byte b : bArr) {
if (!isValid) {
break;
}
switch (b) {
case '(':
case '[':
case '{':
ps.push(b);
break;
case ')':
case ']':
case '}':
if (!ps.empty()) {
byte tmpB = ps.pop();
if (tmpB == 40) {
tmpB++;
} else {
tmpB+=2;
}
if (tmpB != b) {
isValid = false;
}
} else {
isValid = false;
}
break;
default:
// do nothing
}
}
if (!ps.empty()) {
isValid = false;
}
return isValid;
}
}
四、总结小记
- 2022/8/9 一场秋雨一场寒
边栏推荐
- Compensation transaction and idempotency guarantee based on CAP components
- 使用注解将EventBus封装抽取到基类
- 大佬们,请教一下,我看官方文档中,sqlserver cdc只支持2012版之后的,对于sqlser
- 水能自发变成“消毒水”,83岁斯坦福教授:揭示冬天容易得流感的部分原因...
- 900页数学论文证明旋转的黑洞不会爆炸,丘成桐:30多年来广义相对论首次重大突破...
- Rust从入门到精通04-数据类型
- 数据挖掘-06
- 批量读取word docx文件指定表格内容,保存在excel文件中
- 合并两个有序列表
- 卷积神经网络表征可视化研究综述(1)
猜你喜欢

K个结点的组内逆序调整

注:检测到当前使用的ADB不是HBuilder内置或自定义ADB:PID为:9544进程名称为:adb.exe 路径为:c:\users\administrator\appdata\local\and

Resolved IndentationError: unindent does not match any oute r indentation Level

张朝阳对话俞敏洪:一边是手推物理公式,一边是古诗信手拈来

How to upload local file trial version in binary mode in ABAP report

Rust从入门到精通04-数据类型

Simple understanding of ThreadLocal

水能自发变成“消毒水”,83岁斯坦福教授:揭示冬天容易得流感的部分原因...

链表噩梦之一?5000多字带你弄清它的来龙去脉

超越CLIP的多模态模型,只需不到1%的训练数据!南加大最新研究来了
随机推荐
你没见过的《老友记》镜头,AI给补出来了|ECCV 2022
Flutter入门进阶之旅(六)Layout Widget
The new features of ABP 6.0.0 - rc. 1
ABAP interview questions: how to use the System CALL interface of the ABAP programming language, direct execution ABAP server operating System's shell command?
两个链表相加
内网穿透工具ngrok使用教程
Customize VIEW to realize in-app message reminder to rotate up and down
Flutter Getting Started and Advanced Tour (7) GestureDetector
新起之秀 DPU,正在掀起数据中心变革!
腾讯欲成育碧最大股东/ 米哈游招NLP内容生成研究员/ AI发现四千余物种濒临灭绝...今日更多新鲜事在此...
已解决IndentationError: unindent does not match any oute r indentation Level
JVM之配置介绍(一)
Simple understanding of ThreadLocal
Resolved IndentationError: unindent does not match any oute r indentation Level
保存Simulink仿真模型为图片或者PDF的方法
26、管道参数替换命令xargs
h264 protocol
WeChat payment development process
[HCIP Continuous Update] Principle and Configuration of IS-IS Protocol
微服务架构的核心关键点