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

116 lines
4.3 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

> **[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/)
>
'('')''{''}''['']'
1:
> : "()"
> : true
2:
> : "(]"
> : false
3:
> : "()]"
> : false
4
> :"()["
>
> :false
ArrayList popfalse34
![](https://img-blog.csdnimg.cn/20210320141414239.gif)
```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();//最后判断是否为空。
}
}
```