algorithm-base/animation-simulation/栈和队列/leetcode20有效的括号.md

116 lines
4.3 KiB
Java
Raw Normal View History

2021-03-20 08:57:12 +00:00
> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
>
>
>
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
#### [20. ](https://leetcode-cn.com/problems/valid-parentheses/)
2021-03-19 10:50:39 +00:00
>
'('')''{''}''['']'
1:
> : "()"
> : true
2:
> : "(]"
> : false
3:
> : "()]"
> : false
4
> :"()["
>
> :false
ArrayList popfalse34
2021-03-20 06:19:50 +00:00
![](https://img-blog.csdnimg.cn/20210320141414239.gif)
2021-03-19 10:50:39 +00:00
```java
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
//循环遍历字符串
for(char ch : s.toCharArray()){
//入栈的三种情况
if (ch == '(' || ch == '[' || ch == '{') {
stack.push(ch);
}
//右括号对比,其中注意为空的情况
if (ch == ')') {
if( stack.isEmpty() || stack.pop() != '(') {
return false;
}
}
if (ch == ']') {
if (stack.isEmpty() || stack.pop() != '[') {
return false;
}
}
if (ch == '}') {
if (stack.isEmpty() || stack.pop() != '{') {
return false;
}
}
}
//遍历结束的情况
if (!stack.isEmpty()) {
return false;
}
return true;
}
}
```
, [ ' ] ' ] false
```java
class Solution {
public boolean isValid(String s) {
LinkedList<Character> stack = new LinkedList<>();
//遍历字符串
for (char ch : s.toCharArray()) {
//遍历到左括号时右括号入栈,右括号来对比时,只需要对比是否相同。
if (ch == '[') stack.push(']');
else if (ch == '(') stack.push(')');
else if (ch == '{') stack.push('}');
//当ch为右括号时如果为空或不对应则返回false;
else if (stack.isEmpty() || ch != stack.pop()) return false;
}
return stack.isEmpty();//最后判断是否为空。
}
}
```