Leetcode20括号匹配
static boolean isValid(String s) {
if (s.length()<=1){
return false;
}
HashMap<Character, Character> m = new HashMap<>();
Stack<Character> stack = new Stack<>();
m.put('(',')');
m.put('{', '}');
m.put('[', ']');
for (int i=0;i<s.length();i++){
char temp=s.charAt(i);
if (m.containsKey(temp)){
stack.push(temp);
}else {
if (stack.isEmpty()){
return false;
}
char left=stack.pop();
char right=m.get(left);
if (temp!=right){
return false;
}
}
}
return stack.isEmpty();
}
leetcode155最小栈
class MinStack {
Stack stack,minS;
public MinStack() {
stack=new <Integer>Stack();
minS=new Stack<Integer>();
minS.push(Integer.MAX_VALUE);
}
public void push(int val) {
stack.push(val);
minS.push(Math.min((Integer) minS.peek(),val));
}
public void pop() {
minS.pop();
stack.pop();
}
public int top() {
return (int)stack.peek();
}
public int getMin() {
return (int) minS.peek();
}
}
Leetcode716最大栈
和最小站相同思路(会超时)
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> temp=new Stack<>();
while (top()!=max){
temp.push(pop());
}
pop();
while (!temp.isEmpty()){
push(temp.pop());
}
return max;
}
}
Leetcode官方题解
class MaxStack2 {
private TreeSet<int[]> stack;
private TreeSet<int[]> values;
private int cnt;
public MaxStack2() {
Comparator<int[]> comp = (a, b) -> {
return a[0] == b[0] ? a[1] - b[1] : a[0] - b[0];
};
stack = new TreeSet<>(comp);
values = new TreeSet<>(comp);
cnt = 0;
}
public void push(int x) {
stack.add(new int[] { cnt, x });
values.add(new int[] { x, cnt });
cnt++;
}
public int pop() {
int[] pair = stack.pollLast();
values.remove(new int[] { pair[1], pair[0] });
return pair[1];
}
public int top() {
return stack.last()[1];
}
public int peekMax() {
return values.last()[0];
}
public int popMax() {
int[] pair = values.pollLast();
stack.remove(new int[] { pair[1], pair[0] });
return pair[0];
}
}