括号匹配问题
通过栈的先进后出的特性,可用来作为数字匹配作用,回文作用
boolean isValid(String s) { if(s.length()<=1){ return false; } //类似一个注册中心 Map<Character,Character> smap = new HashMap<>(); smap.put('(',')'); smap.put('{','}'); smap.put('[',']'); Stack<Character> stack = new Stack<>(); for(int i=0;i<s.length();i++){ char item = s.charAt(i); //满足则进入栈中 if(smap.containsKey(item)){ stack.push(item); }else{ //开始匹配右侧符号 if(!stack.isEmpty()){ Character left = stack.pop(); //找到是否符合的元素 char rightchar = smap.get(left); if(rightchar != item){ return false; } //如果栈内没有元素,则无法匹配 }else { return false; } } } return stack.isEmpty(); }
最小栈
思想:能够最简单的找出栈内的最小值
栈只能获取栈顶元素,那么只要保持每次栈顶元素为最小值就可以了
每次入栈都与栈内元素比较即可,取最小值。
class MinStack { Deque<Integer> xStack; Deque<Integer> minStack; public MinStack() { xStack = new LinkedList<Integer>(); minStack = new LinkedList<Integer>(); //来处理其刚开始入栈值 minStack.push(Integer.MAX_VALUE); } public void push(int x) { xStack.push(x); minStack.push(Math.min(minStack.peek(), x)); } public void pop() { xStack.pop(); minStack.pop(); } public int top() { return xStack.peek(); } public int getMin() { return minStack.peek(); } }
最大栈
和最小栈的思维一样
class MaxStack { Stack<Integer> stack; Stack<Integer> maxStack; public MaxStack() { stack = new Stack(); maxStack = new Stack(); } public void push(int x) { int max = maxStack.isEmpty() ? x : maxStack.peek(); maxStack.push(max > x ? max : x); stack.push(x); } public int pop() { maxStack.pop(); return stack.pop(); } public int top() { return stack.peek(); } public int peekMax() { return maxStack.peek(); } public int popMax() { int max = peekMax(); Stack<Integer> buffer = new Stack(); while (top() != max) buffer.push(pop()); pop(); while (!buffer.isEmpty()) push(buffer.pop()); return max; } }