当前位置:网站首页>LeetCode20.有效的括号
LeetCode20.有效的括号
2022-07-05 12:39:00 【厚积薄发ض】
有效的括号
-->20. 有效的括号
这个也是栈的应用经典问题
输入:s = "( )" 输出:true 输入:s = "( )[ ]{ }" 输出:true
输入:s = "( ]" 输出:false 输入:s = "( [ ) ]" 输出:false
输入:s = "{ [ ] }" 输出:true
这个题就是一共有三种括号【】{} ()然后这三个可以混合也可以不混合,看是否是匹配的?
思路:
左括号都入栈,然后看遍历的字符是否与其匹配,如果匹配将栈顶左括号弹出继续遍历,如果最后栈中还有元素,或者还有没遍历完的字符串但栈已经为空都是不匹配的

class Solution {
public boolean isValid(String s) {
//如果是左括号就入栈
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(stack.empty()){
//如果栈为空,无法比较
return false;
}else {
//栈不为空看是否是匹配的情况
if((stack.peek()=='('&&s.charAt(i)==')')
||(stack.peek()=='{'&&s.charAt(i)=='}')||
(stack.peek()=='['&&s.charAt(i)==']')){
stack.pop();
}else {
//如果相等弹出栈顶元素
return false;
}
}
}
}
return stack.empty();
}
}边栏推荐
- Docker configures redis and redis clusters
- mysql拆分字符串做条件查询
- 实战模拟│JWT 登录认证
- Taobao short videos are automatically released in batches without manual RPA open source
- 《信息系统项目管理师》备考笔记---信息化知识
- 前几年外包干了四年,秋招感觉人生就这样了..
- Distributed solution - Comprehensive decryption of distributed task scheduling platform -xxljob
- Difference between JUnit theories and parameterized tests
- Neural network of PRML reading notes (1)
- 深度长文探讨Join运算的简化和提速
猜你喜欢

《信息系统项目管理师》备考笔记---信息化知识

Research: data security tools cannot resist blackmail software in 60% of cases

RHCAS6

Laravel文档阅读笔记-mews/captcha的使用(验证码功能)

Taobao, pinduoduo, jd.com, Doudian order & Flag insertion remarks API solution

VoneDAO破解组织发展效能难题

Super efficient! The secret of swagger Yapi
![[cloud native] event publishing and subscription in Nacos -- observer mode](/img/0f/34ab42b7fb0085f58f36eb67b6f107.png)
[cloud native] event publishing and subscription in Nacos -- observer mode

Oppo Xiaobu launched Obert, a large pre training model, and promoted to the top of kgclue

Install rhel8.2 virtual machine
随机推荐
Storage Basics
NFT: how to make money with unique assets?
Using docker for MySQL 8.0 master-slave configuration
Principle of universal gbase high availability synchronization tool in Nanjing University
Database connection pool & jdbctemplate
Distributed solution - distributed session consistency problem
Introduction to the principle of DNS
I'm doing open source in Didi
Insmod prompt invalid module format
Why is your next computer a computer? Explore different remote operations
Keras implements verification code identification
I met Tencent in the morning and took out 38K, which showed me the basic smallpox
Resnet18 actual battle Baoke dream spirit
Shi Zhenzhen's 2021 summary and 2022 outlook | colorful eggs at the end of the article
Kotlin流程控制、循环
关于 SAP UI5 getSAPLogonLanguage is not a function 的错误消息以及 API 版本的讨论
研究:数据安全工具在 60% 的情况下无法抵御勒索软件
Talk about my drawing skills in my writing career
SAP UI5 ObjectPageLayout 控件使用方法分享
Distributed solution - distributed lock solution - redis based distributed lock implementation