20.有效的括号
使用栈:
class Solution {public boolean isValid(String s) {Stack<Character> stack = new Stack<>();int num = s.length();for(int i = 0;i<num;i++){char c = s.charAt(i);if(c=='('||c=='['||c=='{'){stack.push(c);}else if(stack.isEmpty() ||c==')' && stack.pop()!='(' || c==']'&&stack.pop()!='['||c=='}'&&stack.pop()!='{'){return false;}}return stack.isEmpty();}
}
利用哈希表+栈:
class Solution {public boolean isValid(String s) {int n = s.length();if(n % 2 == 1){return false;}Map<Character, Character> map = new HashMap<Character, Character>() {{// 将 })] 作为keyput('}', '{');put(']', '[');put(')', '(');}};// 新建一个栈Deque<Character> stack = new LinkedList<Character>();for (int i = 0; i < n; i++) {char c = s.charAt(i);// 如果c是 })], 则判断, 否则说明是({[ , 直接入栈if(map.containsKey(c)){// stack.peek() 查询栈首元素if(stack.isEmpty() || stack.peek() != map.get(c)){return false;}// 将栈顶移除(先进后出,栈顶是最接近 c 的左括号)stack.pop();}else{// 说明c是({[ , 直接入栈stack.push(c);}}return stack.isEmpty();}
}
栈的链表初始化:
Deque<Character> stack = new LinkedList<Character>();
Java官方推荐使用Deque替代Stack使用,Java堆栈Stack类已经过时
Deque是一个双端队列接口,继承自Queue接口
Deque的实现类是LinkedList、ArrayDeque、LinkedBlockingDeque,但是一般常用LinkedList实现接口
- LinkedList大小可变的链表双端队列,允许元素为null
- ArrayDeque 大下可变的数组双端队列,不允许 null
stack.peek()
:查询栈首元素