1. 题目

2. 思路
(1) HashMap+栈
- 利用HashMap存储左右括号的映射关系,利用栈先进后出的特性进行匹配。
3. 代码
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
public class Test {
public static void main(String[] args) {
}
}
class Solution {
public boolean isValid(String s) {
if (s.length() % 2 != 0) {
return false;
}
Map<Character, Character> map = new HashMap<>();
map.put('(', ')');
map.put('{', '}');
map.put('[', ']');
Deque<Character> stack = new LinkedList<>();
char ch;
for (int i = 0; i < s.length(); i++) {
ch = s.charAt(i);
if (map.containsKey(ch)) {
stack.push(ch);
} else if (stack.isEmpty() || map.get(stack.pop()) != ch) {
return false;
}
}
if (!stack.isEmpty()) {
return false;
}
return true;
}
}