白银——栈的经典算法问题
括号匹配问题
题目:leetCode:20(类似题目:22,32,301,856)
思路:
- 用hashMap把所有符号做存储
- 然后在用栈来对比,遇到左半边就入栈,遇到右半边的栈就匹配,匹配成功出栈,不成功返回
解法:
/**
* 括号匹配问题
* @param s
* @return
*/
public boolean isValid(String s) {
if (s.length()<2){
return false;
}
//把所用可能的括号用map储存,key为左括号,value为右括号
HashMap<Character, Character> map = new HashMap<>(12);
map.put('(',')');
map.put('{','}');
map.put('[',']');
//初始化stack
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char charAt = s.charAt(i);
if (map.containsKey(charAt)){
stack.push(charAt);
}else {
if (!stack.isEmpty()){
Character left = stack.pop();
if (map.get(left)!=charAt){
return false;
}
}else {
return false;
}
}
}
return stack.isEmpty();
}
最小栈
题目:LeetCode:155
思路:
- 创建两个栈,一个存储正常的值,一个储存最小值,并且两个栈要同步入栈出栈
解法:
class MinStack {
Deque<Integer> xStack;
Deque<Integer> minStack;
public MinStack() {
xStack = new LinkedList<>();
minStack = new LinkedList<>();
minStack.push(Integer.MAX_VALUE);
}
public void push(int val) {
xStack.push(val);
int min = Math.min(minStack.peek(), val);
minStack.push(min);
}
public void pop() {
xStack.pop();
minStack.pop();
}
public int top() {
return xStack.peek();
}
public int getMin() {
return minStack.peek();
}
}
最大栈
题目:LeetCode716
思路:
- 跟最小栈的思路相同,但是最后的popMax要改造一下,把最大栈出栈之后,要把之前出栈过的栈重新入栈
解法:
public class MinStack {
Deque<Integer> xStack;
Deque<Integer> maxStack;
public MinStack() {
xStack = new LinkedList<>();
maxStack = new LinkedList<>();
}
public void push(int val) {
int max = maxStack.isEmpty() ? val : maxStack.peek();
xStack.push(val);
maxStack.push(max>val? max:val);
}
public int pop() {
maxStack.pop();
return xStack.pop();
}
public int top() {
return xStack.peek();
}
public int peekMax() {
return maxStack.peek();
}
public int popMax() {
int max = peekMax();
Stack<Object> buffer = new Stack<>();
while (top()!max)buffer.push(pop());
pop();
while (!buffer.isEmpty())push(buffer.pop());
return max;
}
}