当前位置:网站首页>【LeetCode】2. Valid parentheses · valid parentheses
【LeetCode】2. Valid parentheses · valid parentheses
2022-07-03 07:42:00 【AQin1012】
Title Description
Description in English
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
English address
https://leetcode.com/problems/valid-parentheses/
https://leetcode.com/problems/valid-parentheses/
Description of Chinese version
Given one only includes '(',')','{','}','[',']' String s , Determines whether the string is valid .
Valid string needs to meet :
Opening parentheses must be closed with closing parentheses of the same type .
The left parenthesis must be closed in the correct order .
Example 1:
Input :s = "()"
Output :true
Example 2:
Input :s = "()[]{}"
Output :true
Example 3:
Input :s = "(]"
Output :false
Example 4:
Input :s = "([)]"
Output :false
Example 5:
Input :s = "{[]}"
Output :true
Constraints· Tips :
1 <= s.length <= 104
s Brackets only '()[]{}' form
Address of Chinese version
https://leetcode.cn/problems/valid-parentheses/
https://leetcode.cn/problems/valid-parentheses/
Their thinking
Because it needs to be closed in sequence , That is, the first right parenthesis needs to be paired with the nearest left parenthesis , And there are no left or right parentheses left at the end , Therefore, we can take advantage of the first in and last out feature of the stack structure , Push unpaired parentheses onto the stack , Every time you read a new bracket , Just check whether it matches the top element , If it matches, the element at the top of the stack will pop up , If there is no match, the current element will be put on the stack , Then go on to the next , Until there are no new elements , If the stack is empty at this time , Then the string is valid , Otherwise, it is invalid .
How to solve the problem
My version

public static boolean isValid(String s) {
Stack stack = new Stack();
// stack.push(s.charAt(0));
// Get the ASCII Code value
int parenthesesLeft = Integer.valueOf('(');
int parenthesesRight = Integer.valueOf(')');
int middleBracketLeft = Integer.valueOf('[');
int middleBracketRight = Integer.valueOf(']');
int curlyBracketLeft = Integer.valueOf('{');
int curlyBracketRight = Integer.valueOf('}');
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
int value = Integer.valueOf(c);
// Get the ASCII code
char peek;
int peekValue;
// The left half is directly stacked , Check whether the right half matches the top element
if (value == parenthesesLeft || value == middleBracketLeft || value == curlyBracketLeft) {
stack.push(c);
continue;
} else if (value == parenthesesRight || value == middleBracketRight || value == curlyBracketRight) {
if (stack.isEmpty()) {
return false;
}
peek = (char) stack.peek();
peekValue = Integer.valueOf(peek);
if (value == parenthesesRight) {
if (peekValue == parenthesesLeft) {
stack.pop();
continue;
}
} else if (value == middleBracketRight) {
if (peekValue == middleBracketLeft) {
stack.pop();
continue;
}
} else if (value == curlyBracketRight) {
if (peekValue == curlyBracketLeft) {
stack.pop();
continue;
}
}
return false;
}
}
if (stack.isEmpty()) {
return true;
} else {
return false;
}
}Official edition

public boolean isValid(String s) {
int n = s.length();
if (n % 2 == 1) {
return false;
}
Map<Character, Character> pairs = new HashMap<Character, Character>() {
{
put(')', '(');
put(']', '[');
put('}', '{');
}};
Deque<Character> stack = new LinkedList<Character>();
for (int i = 0; i < n; i++) {
char ch = s.charAt(i);
if (pairs.containsKey(ch)) {
if (stack.isEmpty() || stack.peek() != pairs.get(ch)) {
return false;
}
stack.pop();
} else {
stack.push(ch);
}
}
return stack.isEmpty();
}
Students with better methods are welcome to poke in the comment area *〜(ゝ.∂)~~~
边栏推荐
- Technical dry goods Shengsi mindspire innovation model EPP mvsnet high-precision and efficient 3D reconstruction
- Leetcode 198: 打家劫舍
- The concept of C language pointer
- Professor Zhang Yang of the University of Michigan is employed as a visiting professor of Shanghai Jiaotong University, China (picture)
- 【CoppeliaSim4.3】C#调用 remoteApi控制场景中UR5
- PHP微信抢红包的算法
- Structure of golang
- C2 several methods of merging VCF files
- Vertx's responsive MySQL template
- 圖像識別與檢測--筆記
猜你喜欢

Go language foundation ----- 02 ----- basic data types and operators

Go language foundation ------ 14 ------ gotest

技术干货|利用昇思MindSpore复现ICCV2021 Best Paper Swin Transformer
![[Development Notes] cloud app control on device based on smart cloud 4G adapter gc211](/img/55/fea5fe315932b92993d21f861befbe.png)
[Development Notes] cloud app control on device based on smart cloud 4G adapter gc211

Technical dry goods Shengsi mindspire elementary course online: from basic concepts to practical operation, 1 hour to start!

Research shows that breast cancer cells are more likely to enter the blood when patients sleep

技术干货|百行代码写BERT,昇思MindSpore能力大赏

【MindSpore论文精讲】AAAI长尾问题中训练技巧的总结

PAT甲级 1028 List Sorting

【LeetCode】2. Valid Parentheses·有效的括号
随机推荐
VMware network mode - bridge, host only, NAT network
Web router of vertx
一篇文章让你读懂-曼彻斯特编码
Project experience sharing: Based on mindspore, the acoustic model is realized by using dfcnn and CTC loss function
项目经验分享:实现一个昇思MindSpore 图层 IR 融合优化 pass
技术干货|昇思MindSpore Lite1.5 特性发布,带来全新端侧AI体验
The concept of C language pointer
An overview of IfM Engage
基于RNA的新型癌症疗法介绍
Shengsi mindspire is upgraded again, the ultimate innovation of deep scientific computing
How long is the fastest time you can develop data API? One minute is enough for me
技术干货|关于AI Architecture未来的一些思考
Go language foundation ----- 06 ----- anonymous fields, fields with the same name
Go language foundation ------ 12 ------ JSON
华为S5700交换机初始化和配置telnet,ssh用户方法
Go language foundation ----- 16 ----- goroutine, GPM model
Read config configuration file of vertx
PHP微信抢红包的算法
【LeetCode】3. Merge Two Sorted Lists·合并两个有序链表
PAT甲级 1027 Colors in Mars