当前位置:网站首页>【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();
}
欢迎有更好方法的同学评论区戳戳*〜(ゝ。∂)~~~
边栏推荐
- 不出网上线CS的各种姿势
- Use of file class
- Analysis of the eighth Blue Bridge Cup single chip microcomputer provincial competition
- How long is the fastest time you can develop data API? One minute is enough for me
- Map interface and method
- Technical dry goods Shengsi mindspire lite1.5 feature release, bringing a new end-to-end AI experience
- Industrial resilience
- Read config configuration file of vertx
- Lucene skip table
- Responsive MySQL of vertx
猜你喜欢
![PdfWriter. GetInstance throws system Nullreferenceexception [en] pdfwriter GetInstance throws System. NullRef](/img/65/1f28071fc15e76abb37f1b128e1d90.jpg)
PdfWriter. GetInstance throws system Nullreferenceexception [en] pdfwriter GetInstance throws System. NullRef

技术干货 | AlphaFold/ RoseTTAFold开源复现(2)—AlphaFold流程分析和训练构建

Common methods of file class

TCP cumulative acknowledgement and window value update

专题 | 同步 异步

技术干货|关于AI Architecture未来的一些思考

Map interface and method

技术干货|昇思MindSpore NLP模型迁移之Bert模型—文本匹配任务(二):训练和评估

Technical dry goods | hundred lines of code to write Bert, Shengsi mindspire ability reward

《指环王:力量之戒》新剧照 力量之戒铸造者亮相
随机推荐
Read config configuration file of vertx
Custom generic structure
Hnsw introduction and some reference articles in lucene9
【开发笔记】基于机智云4G转接板GC211的设备上云APP控制
New stills of Lord of the rings: the ring of strength: the caster of the ring of strength appears
Arduino 软串口通信 的几点体会
Beginners use Minio
技术干货|昇思MindSpore初级课程上线:从基本概念到实操,1小时上手!
Segment read
Summary of Arduino serial functions related to print read
Technical dry goods Shengsi mindspire innovation model EPP mvsnet high-precision and efficient 3D reconstruction
【CoppeliaSim4.3】C#调用 remoteApi控制场景中UR5
《指环王:力量之戒》新剧照 力量之戒铸造者亮相
Technical dry goods | reproduce iccv2021 best paper swing transformer with Shengsi mindspire
Jeecg request URL signature
JUnit unit test of vertx
Es writing fragment process
技术干货|利用昇思MindSpore复现ICCV2021 Best Paper Swin Transformer
Logging log configuration of vertx
Analysis of the eighth Blue Bridge Cup single chip microcomputer provincial competition