当前位置:网站首页>【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 *〜(ゝ.∂)~~~
边栏推荐
- Structure of golang
- Lucene skip table
- Hisat2 - stringtie - deseq2 pipeline for bulk RNA seq
- 項目經驗分享:實現一個昇思MindSpore 圖層 IR 融合優化 pass
- Go language foundation ----- 04 ----- closure, array slice, map, package
- Leetcode 198: 打家劫舍
- Beginners use Minio
- Qtip2 solves the problem of too many texts
- Lucene hnsw merge optimization
- The babbage industrial policy forum
猜你喜欢

Technical dry goods Shengsi mindspire lite1.5 feature release, bringing a new end-to-end AI experience

Go language foundation ----- 07 ----- method

【LeetCode】2. Valid Parentheses·有效的括号

Shengsi mindspire is upgraded again, the ultimate innovation of deep scientific computing

Go language foundation ------17 ----- channel creation, read-write, security shutdown, multiplexing select

Iterm2设置
![[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

Go language foundation ----- 13 ----- file

Analysis of the problems of the 11th Blue Bridge Cup single chip microcomputer provincial competition

Epoll related references
随机推荐
s7700设备如何清除console密码
Analysis of the problems of the 10th Blue Bridge Cup single chip microcomputer provincial competition
Project experience sharing: Based on mindspore, the acoustic model is realized by using dfcnn and CTC loss function
項目經驗分享:實現一個昇思MindSpore 圖層 IR 融合優化 pass
Pgadmin 4 v6.11 release, PostgreSQL open source graphical management tool
Go language - loop statement
技术干货|昇思MindSpore算子并行+异构并行,使能32卡训练2420亿参数模型
研究显示乳腺癌细胞更容易在患者睡觉时进入血液
技术干货 | AlphaFold/ RoseTTAFold开源复现(2)—AlphaFold流程分析和训练构建
Hnsw introduction and some reference articles in lucene9
Responsive MySQL of vertx
Lucene hnsw merge optimization
Technical dry goods | reproduce iccv2021 best paper swing transformer with Shengsi mindspire
Technical dry goods | hundred lines of code to write Bert, Shengsi mindspire ability reward
技术干货|昇思MindSpore NLP模型迁移之LUKE模型——阅读理解任务
技术干货|昇思MindSpore可变序列长度的动态Transformer已发布!
Sent by mqtt client server of vertx
Partage de l'expérience du projet: mise en œuvre d'un pass optimisé pour la fusion IR de la couche mindstore
An overview of IfM Engage
输入三次猜一个数字