当前位置:网站首页>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 一场秋雨一场寒
边栏推荐
- go基础之web获取参数
- Flutter入门进阶之旅(五)Image Widget
- MySQL备份与恢复 (转载非原创)
- Say goodbye to the AI era of hand looms
- 用 API Factory 产品生成 API 文档
- Flutter入门进阶之旅(四)文本输入Widget TextField
- 鹅厂机器狗花式穿越10m梅花桩:前空翻、单桩跳、起身作揖...全程不打一个趔趄...
- Flutter Getting Started and Advanced Tour (3) Text Widgets
- 8、IDEA提交代码出现: Fetch failed fatal: Could not read from remote repository
- Flutter入门进阶之旅(十)Dialog&Toast
猜你喜欢
随机推荐
1-hour live broadcast recruitment order: industry big names share dry goods, and enterprise registration opens丨qubit·viewpoint
听声辨物,这是AI视觉该干的???|ECCV 2022
Flutter入门进阶之旅(二)Hello Flutter
Flutter Getting Started and Advanced Tour (4) Text Input Widget TextField
FFmpeg库在win10上配置使用(不配置libx264)
【HCIP持续更新】IS-IS协议原理与配置
二叉树的序列化和反序列化
Resolved IndentationError: unindent does not match any oute r indentation Level
World's 4th mad scientist dies on his 103rd birthday
Batch大小不一定是2的n次幂!ML资深学者最新结论
位图与位运算
900页数学论文证明旋转的黑洞不会爆炸,丘成桐:30多年来广义相对论首次重大突破...
Too much volume... Tencent was asked on the side that the memory was full, what would happen?
发明时代,「幂集创新」事关你我
正则引擎的几种分类
水能自发变成“消毒水”,83岁斯坦福教授:揭示冬天容易得流感的部分原因...
Rust从入门到精通04-数据类型
ViewPager fragments of nested data blank page abnormal problem analysis
AI篮球裁判火了,走步算得特别准,就问哈登慌不慌
Intranet penetration tool ngrok usage tutorial