1. 括号配对问题
首先判断字符串中如果是左括号就放入栈中,如果不是左括号判断是否与栈顶元素匹配,不是直接返回false。是的话继续判断。注意如果判断完之后top不为0则说明左括号多,这种情况还是返回false。
1.
class Solution {
public boolean isValid(String s) {
if(s.isEmpty())
return true;
Stack<Character> stack=new Stack<Character>();
for(char c:s.toCharArray()){
if(c=='(')
stack.push(')');
else if(c=='{')
stack.push('}');
else if(c=='[')
stack.push(']');
else if(stack.empty()||c!=stack.pop())
return false;
}
return stack.empty();
}
}
class MyStack {
private Queue<Integer> a;//输入队列
private Queue<Integer> b;//输出队列
public MyStack() {
a = new LinkedList<>();
b = new LinkedList<>();
}
public void push(int x) {
a.offer(x);
// 将b队列中元素全部转给a队列
while(!b.isEmpty())
a.offer(b.poll());
// 交换a和b,使得a队列没有在push()的时候始终为空队列
Queue temp = a;
a = b;
b = temp;
}
public int pop() {
return b.poll();
}
public int top() {
return b.peek();
}
public boolean empty() {
return b.isEmpty();
}
}
class MyQueue {
private Stack<Integer> a;
private Stack<Integer> b;
public MyQueue() {
a = new Stack<>();
b = new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
a.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
//判断b栈是否为空,如果b栈不为空,那么说明a栈的元素已经倒入b了,所以直接弹出b即可
if(b.isEmpty()){
while(!a.isEmpty()){
b.push(a.pop());
}
}
return b.pop();
}
/** Get the front element. */
public int peek() {
if(b.isEmpty()){
while(!a.isEmpty()){
b.push(a.pop());
}
}
return b.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return a.isEmpty() && b.isEmpty();
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
4. 最小栈
一次插入两个元素,第一个是本该插入的元素,第二个是当前最小元素。
class MinStack {
/** initialize your data structure here. */
private Stack<Integer> stack = new Stack<>();
public MinStack() {
}
//-2 0 -3
//-2 -2 0 -2 -3 -3
public void push(int x) {
if (stack.isEmpty()){
stack.push(x);
stack.push(x);
}else{
int temp = stack.peek();//-2
stack.push(x);//0
if (x < temp){
stack.push(x);
}else{
stack.push(temp);
}
}
}
public void pop() {
stack.pop();
stack.pop();
}
public int top() {
int temp = stack.pop();
int result = stack.peek();
stack.push(temp);
return result;
}
public int getMin() {
return stack.peek();
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/