有效的括号

括号可以互相包含,但不能参差摆放

示例 1:

**输入:**s = “()”

**输出:**true

示例 2:

**输入:**s = “()[]{}”

**输出:**true

示例 3:

**输入:**s = “(]”

**输出:**false

栈 + 哈希映射

遇到左括号 → 入栈
遇到右括号 → 检查栈顶是否配对,配对则出栈,否则无效
遍历完 → 栈必须为空

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.util.*;

class Solution {
public boolean isValid(String s) {
Map<Character, Character> map = new HashMap<>();
map.put(')', '(');
map.put(']', '[');
map.put('}', '{');

Deque<Character> stack = new ArrayDeque<>();

for (char c : s.toCharArray()) {
if (map.containsKey(c)) { // 是右括号
if (stack.isEmpty() || stack.pop() != map.get(c)) {
return false;
}
} else { // 是左括号
stack.push(c);
}
}
return stack.isEmpty();
}
}