当前位置:网站首页>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();
}
}边栏推荐
- Super efficient! The secret of swagger Yapi
- mysql拆分字符串做条件查询
- DNS的原理介绍
- SAP UI5 FlexibleColumnLayout 控件介绍
- Compile kernel modules separately
- NFT: how to make money with unique assets?
- A few years ago, I outsourced for four years. Qiu Zhao felt that life was like this
- RHCAS6
- Detailed structure and code of inception V3
- Talk about my drawing skills in my writing career
猜你喜欢

The relationship between the size change of characteristic graph and various parameters before and after DL convolution operation

滴滴开源DELTA:AI开发者可轻松训练自然语言模型

上午面了个腾讯拿 38K 出来的,让我见识到了基础的天花

RHCSA5

2021.12.16-2021.12.20 empty four hand transaction records

JDBC exercise - query data encapsulated into object return & simple login demo

DNS的原理介绍

石臻臻的2021总结和2022展望 | 文末彩蛋

SAP self-development records user login logs and other information

Oppo Xiaobu launched Obert, a large pre training model, and promoted to the top of kgclue
随机推荐
Introduction to relational model theory
I met Tencent in the morning and took out 38K, which showed me the basic smallpox
Taobao, pinduoduo, jd.com, Doudian order & Flag insertion remarks API solution
Redis master-slave configuration and sentinel mode
C alarm design
Neural network of PRML reading notes (1)
RHCSA2
Taobao order interface | order flag remarks, may be the most stable and easy-to-use interface
Distributed solution - completely solve website cross domain requests
Comprehensive upgrade of Taobao short video photosynthetic platform
Resnet18 actual battle Baoke dream spirit
RHCSA3
Pytoch loads the initialization V3 pre training model and reports an error
View and terminate the executing thread in MySQL
跨平台(32bit和64bit)的 printf 格式符 %lld 输出64位的解决方式
Shi Zhenzhen's 2021 summary and 2022 outlook | colorful eggs at the end of the article
2021-12-22 transaction record
Why is your next computer a computer? Explore different remote operations
Principle of universal gbase high availability synchronization tool in Nanjing University
Introduction to the principle of DNS