当前位置:网站首页>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 一场秋雨一场寒
边栏推荐
- 900页数学论文证明旋转的黑洞不会爆炸,丘成桐:30多年来广义相对论首次重大突破...
- 鹅厂机器狗花式穿越10m梅花桩:前空翻、单桩跳、起身作揖...全程不打一个趔趄...
- Intra-group reverse order adjustment of K nodes
- JVM之配置介绍(一)
- LnReader编译
- Two minutes recording can pass by second language!The volcano how to practice and become voice tone reproduction technology?
- Flutter入门进阶之旅(五)Image Widget
- 发明时代,「幂集创新」事关你我
- 工作任务统计
- ViewPager fragments of nested data blank page abnormal problem analysis
猜你喜欢
中断系统结构及中断控制详解
工作任务统计
The new features of ABP 6.0.0 - rc. 1
超越CLIP的多模态模型,只需不到1%的训练数据!南加大最新研究来了
Resolved IndentationError: unindent does not match any oute r indentation Level
Rust from entry to proficient 04 - data types
内网穿透工具ngrok使用教程
ABAP 面试题:如何使用 ABAP 编程语言的 System CALL 接口,直接执行 ABAP 服务器所在操作系统的 shell 命令?
8、IDEA提交代码出现: Fetch failed fatal: Could not read from remote repository
Go 事,如何成为一个Gopher ,并在7天找到 Go 语言相关工作,第1篇
随机推荐
数据挖掘-05
数据挖掘-06
位图与位运算
LnReader编译
FFmpeg在win10上编译安装(配置libx264)
Batch大小不一定是2的n次幂!ML资深学者最新结论
报告:想学AI的学生数量已涨200%,老师都不够用了
【微服务~远程调用】整合RestTemplate、WebClient、Feign
Go 事,如何成为一个Gopher ,并在7天找到 Go 语言相关工作,第1篇
ERP不规范,同事两行泪 (转载非原创)
Do you know the difference between comments, keywords, and identifiers?
又有大厂员工连续加班倒下/ 百度搜狗取消快照/ 马斯克生父不为他骄傲...今日更多新鲜事在此...
使用RecyclerView实现三级折叠列表
Flutter入门进阶之旅(三)Text Widgets
AQS Synchronization Component - FutureTask Analysis and Use Cases
工作任务统计
SQL Server查询优化 (转载非原创)
AI篮球裁判火了,走步算得特别准,就问哈登慌不慌
Flutter Getting Started and Advanced Tour (7) GestureDetector
ABP 6.0.0-rc.1的新特性