当前位置:网站首页>【LeetCode】2. Valid Parentheses·有效的括号
【LeetCode】2. Valid Parentheses·有效的括号
2022-07-03 07:34:00 【AQin1012】
题目描述
英文版描述
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.
英文版地址
https://leetcode.com/problems/valid-parentheses/https://leetcode.com/problems/valid-parentheses/
中文版描述
给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
示例 1:
输入:s = "()"
输出:true
示例 2:
输入:s = "()[]{}"
输出:true
示例 3:
输入:s = "(]"
输出:false
示例 4:
输入:s = "([)]"
输出:false
示例 5:
输入:s = "{[]}"
输出:true
Constraints·提示:
1 <= s.length <= 104
s 仅由括号 '()[]{}' 组成
中文版地址
https://leetcode.cn/problems/valid-parentheses/https://leetcode.cn/problems/valid-parentheses/
解题思路
因为需要按顺序闭合,即最先出现的右括号需要能与离他最近的左括号配成对,且到最后无剩余的左括号或者右括号,所以考虑可以利用栈结构先进后出的特性,将未配对的括号压入栈中,每读取一个新的括号,就查看其与栈顶元素是否匹配,匹配则弹出栈顶元素,不匹配则将当前元素入栈,然后继续下一个,直到没有新元素了,如果此时栈为空,则该字符串有效,反之无效。
解题方法
俺这版
public static boolean isValid(String s) {
Stack stack = new Stack();
// stack.push(s.charAt(0));
// 分别获取各个括号的ASCII码值
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);
// 获取栈顶元素的ASCII码
char peek;
int peekValue;
// 左半边的直接入栈,右半边的查看与栈顶元素是否匹配
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;
}
}
官方版
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();
}
欢迎有更好方法的同学评论区戳戳*〜(ゝ。∂)~~~
边栏推荐
- Dora (discover offer request recognition) process of obtaining IP address
- Arduino Serial系列函数 有关print read 的总结
- 技术干货|关于AI Architecture未来的一些思考
- Traversal in Lucene
- Topic | synchronous asynchronous
- Industrial resilience
- Segment read
- New stills of Lord of the rings: the ring of strength: the caster of the ring of strength appears
- 图像识别与检测--笔记
- VMWare网络模式-桥接,Host-Only,NAT网络
猜你喜欢
截图工具Snipaste
Paper learning -- Study on the similarity of water level time series of Xingzi station in Poyang Lake
Leetcode 198: house raiding
Leetcode 198: 打家劫舍
Use of file class
带你全流程,全方位的了解属于测试的软件事故
Common methods of file class
Collector in ES (percentile / base)
技术干货|昇思MindSpore创新模型EPP-MVSNet-高精高效的三维重建
Dora (discover offer request recognition) process of obtaining IP address
随机推荐
Inverted chain disk storage in Lucene (pfordelta)
技术干货|昇思MindSpore可变序列长度的动态Transformer已发布!
How long is the fastest time you can develop data API? One minute is enough for me
Beginners use Minio
New stills of Lord of the rings: the ring of strength: the caster of the ring of strength appears
What did the DFS phase do
带你全流程,全方位的了解属于测试的软件事故
Circuit, packet and message exchange
The concept of C language pointer
Jeecg request URL signature
Paper learning -- Study on the similarity of water level time series of Xingzi station in Poyang Lake
[mindspire paper presentation] summary of training skills in AAAI long tail problem
Segment read
c语言指针的概念
技术干货 | AlphaFold/ RoseTTAFold开源复现(2)—AlphaFold流程分析和训练构建
The difference between typescript let and VaR
Partage de l'expérience du projet: mise en œuvre d'un pass optimisé pour la fusion IR de la couche mindstore
Operation and maintenance technical support personnel have hardware maintenance experience in Hong Kong
Longest common prefix and
C code production YUV420 planar format file