当前位置:网站首页>每日一题-有效的括号-0719
每日一题-有效的括号-0719
2022-08-05 05:17:00 【菜鸡程序媛】
题目
给定一个只包括 ‘(’,‘)’,‘{’,‘}’,‘[’,‘]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
(1)左括号必须用相同类型的右括号闭合。
(2)左括号必须以正确的顺序闭合。
思路
- 初始化栈,用来存储字符串中的字符
- 如果是左面的符号,则入栈;是右面的符号的话,如果当前的栈顶是和右括号匹配的左括号,则将左括号弹出,相互抵消,否则直接入栈,直接返回false
- 最后判断一下栈是否是空的
代码
class Solution {
public boolean isValid(String s) {
if(s == null || s.length() == 0)
return false;
Stack<Character> stack = new Stack<>();
for(int i = 0; i < s.length(); i ++){
if(s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '['){
stack.push(s.charAt(i));
}else if(s.charAt(i) == ')'){
if(!stack.isEmpty() && stack.peek() == '(')
stack.pop();
else{
stack.push(s.charAt(i));
return false;
}
}else if(s.charAt(i) == '}'){
if(!stack.isEmpty() && stack.peek() == '{')
stack.pop();
else{
stack.push(s.charAt(i));
return false;
}
}else{
if(!stack.isEmpty() && stack.peek() == '[')
stack.pop();
else{
stack.push(s.charAt(i));
return false;
}
}
}
return stack.isEmpty();
}
}
边栏推荐
猜你喜欢
【shell编程】第二章:条件测试语句
Detailed explanation of BroadCast Receiver (broadcast)
Machine Learning (1) - Machine Learning Fundamentals
手把手教你搭建小程序
Leetcode刷题——对链表进行插入排序
CVPR best paper winner Huang Gao's team from Tsinghua University presented the first dynamic network review
LeetCode刷题之第74题
LeetCode刷题之第23题
SQL (2) - join window function view
PoE视频监控解决方案
随机推荐
LeetCode刷题之第86题
读论文-Cycle GAN
The University of Göttingen proposed CLIPSeg, a model that can perform three segmentation tasks at the same time
Service
AIDL detailed explanation
【nodejs】第一章:nodejs架构
[Database and SQL study notes] 8. Views in SQL
Tensorflow steps on the pit notes and records various errors and solutions
电子产品量产工具(4)-UI系统实现
LeetCode刷题之第746题
电子产品量产工具(2)- 输入系统实现
栈的应用——力扣 20.有效的括号
【ts】typescript高阶:模版字面量类型
2021电赛资源及经验总结
《基于机器视觉的输电线路交叉点在线测量方法及技术方案》论文笔记
PID详解
MSRA提出学习实例和分布式视觉表示的极端掩蔽模型ExtreMA
表情捕捉的指标/图像的无参考质量评价
C语言联合体union占用空间大小问题
LeetCode刷题之第24题