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 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;
}
}