括号匹配问题
leetcode20:给定一个只包括'(',')','[',']','{','}',的字符串s,判断字符串是否有效。
左括号必须要以相同类型的右括号闭合。
(){}[]
{[()]}
使用map来记录key(左括号)和value(右括号),遇到左括号就入栈,遇到右括号就与栈顶元素比较,不匹配则return false。
public static 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 right = smap.get(item);
if (right!=left){
return false;
}
}else {
return false;
}
}
}
return stack.isEmpty();
}
最小栈
使用辅助栈minStack,在进行stack.push(x)操作时,将x与minStack的peek()进行比较,minStack.push(x>minStack.peek()?minStack.peek():x),可以在初始化时minStack.push(Integer.MAX_VLAUE),或者在每次push()时判断stack是否isEmpty(),没有则直接minStack.push(x),否则进行判断。
import java.util.Deque;
import java.util.LinkedList;
public 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 int pop(){
minStack.pop();
return xStack.pop();
}
public int top(){
return xStack.peek();
}
public int getMin(){
return minStack.peek();
}
}
最大栈
基本同上
public 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);
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()){
stack.push(buffer.pop());
}
return max;
}
}