当前位置:网站首页>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 一场秋雨一场寒
边栏推荐
- Do you know the difference between comments, keywords, and identifiers?
- How to upload local file trial version in binary mode in ABAP report
- Intra-group reverse order adjustment of K nodes
- 字符串转换整数 (atoi)
- ansible-cmdb friendly display ansible collects host information
- 【微服务~远程调用】整合RestTemplate、WebClient、Feign
- Flutter入门进阶之旅(二)Hello Flutter
- 注释、关键字、标识符的区别你知道吗?
- Batch大小不一定是2的n次幂!ML资深学者最新结论
- Flutter入门进阶之旅(七)GestureDetector
猜你喜欢
透明tune proxy
Flutter Getting Started and Advanced Tour (8) Button Widget
MySQL 原理与优化,Group By 优化 技巧
win10编译x264库(也有生成好的lib文件)
AI basketball referee, walking is special, ask harden care don't care
Resolved IndentationError: unindent does not match any oute r indentation Level
苹果Meta都在冲的Pancake技术,中国VR团队YVR竟抢先交出产品答卷
两分钟录音就可秒变语言通!火山语音音色复刻技术如何修炼而成?
报告:想学AI的学生数量已涨200%,老师都不够用了
Flutter入门进阶之旅(八)Button Widget
随机推荐
WeChat payment development process
二叉树的序列化和反序列化
#Internet of Things essay#Xiaoxiong pie equipment development actual combat
Customize VIEW to realize in-app message reminder to rotate up and down
Manchester city launch emotional intelligence scarf can be detected, give the fans
随机快排时间复杂度是N平方?
Flutter入门进阶之旅(十)Dialog&Toast
如何修改data work上jdbc驱动的版本
水能自发变成“消毒水”,83岁斯坦福教授:揭示冬天容易得流感的部分原因...
Intranet penetration tool ngrok usage tutorial
World's 4th mad scientist dies on his 103rd birthday
FFmpeg在win10上编译安装(配置libx264)
Win10 compiles the x264 library (there are also generated lib files)
JVM之配置介绍(一)
腾讯欲成育碧最大股东/ 米哈游招NLP内容生成研究员/ AI发现四千余物种濒临灭绝...今日更多新鲜事在此...
Rust from entry to proficient 04 - data types
你没见过的《老友记》镜头,AI给补出来了|ECCV 2022
Go 事,如何成为一个Gopher ,并在7天找到 Go 语言相关工作,第1篇
用 API Factory 产品生成 API 文档
无重复字符的最长子串