当前位置:网站首页>【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 *〜(ゝ.∂)~~~
边栏推荐
- Iterm2设置
- Qtip2 solves the problem of too many texts
- What did the DFS phase do
- Technical dry goods Shengsi mindspire innovation model EPP mvsnet high-precision and efficient 3D reconstruction
- 在浏览器输入url后执行什么
- Research shows that breast cancer cells are more likely to enter the blood when patients sleep
- 技术干货|昇思MindSpore Lite1.5 特性发布,带来全新端侧AI体验
- Lucene skip table
- 截图工具Snipaste
- Project experience sharing: Based on mindspore, the acoustic model is realized by using dfcnn and CTC loss function
猜你喜欢
【MindSpore论文精讲】AAAI长尾问题中训练技巧的总结
Analysis of the problems of the 10th Blue Bridge Cup single chip microcomputer provincial competition
截图工具Snipaste
[Development Notes] cloud app control on device based on smart cloud 4G adapter gc211
PAT甲级 1029 Median
技术干货|昇思MindSpore创新模型EPP-MVSNet-高精高效的三维重建
技术干货|昇思MindSpore NLP模型迁移之LUKE模型——阅读理解任务
Go language foundation ----- 13 ----- file
Professor Zhang Yang of the University of Michigan is employed as a visiting professor of Shanghai Jiaotong University, China (picture)
Go language foundation ------ 14 ------ gotest
随机推荐
The difference between typescript let and VaR
C2 several methods of merging VCF files
OSPF protocol summary
Industrial resilience
Application of pigeon nest principle in Lucene minshouldmatchsumscorer
研究显示乳腺癌细胞更容易在患者睡觉时进入血液
华为交换机:配置telnet和ssh、web访问
An overview of IfM Engage
HarmonyOS第三次培训笔记
The concept of C language pointer
微软安全响应中心
PDO and SDO concepts
VMware network mode - bridge, host only, NAT network
pgAdmin 4 v6.11 发布,PostgreSQL 开源图形化管理工具
华为交换机配置ssh登录远程管理交换机
Go language foundation ----- 13 ----- file
【MySQL 14】使用DBeaver工具远程备份及恢复MySQL数据库(Linux 环境)
Technical dry goods Shengsi mindspire lite1.5 feature release, bringing a new end-to-end AI experience
技术干货|百行代码写BERT,昇思MindSpore能力大赏
【LeetCode】4. Best Time to Buy and Sell Stock·股票买卖最佳时机