232.用栈实现队列
模拟类型的题目
只要知道栈和队列的结构,用第一个栈模拟时发现能入队但出队时顺序相反了,正好利用栈能翻转输出顺序的特性,创建另一个栈用于输出
注意代码实现中,出队时如果out栈空,需要把所有in栈的元素压入out栈来维护顺序
class MyQueue {
private Stack<Integer> in;
private Stack<Integer> out;
public MyQueue() {
in = new Stack<>();
out = new Stack<>();
}
public void push(int x) {
in.push(x);
}
public int pop() {
if (out.empty()) {
while(!in.empty()) {
int x = in.peek();
out.push(x);
in.pop();
}
}
int res = out.peek();
out.pop();
return res;
}
public int peek() {
if (out.empty()) {
while(!in.empty()) {
int x = in.peek();
out.push(x);
in.pop();
}
}
int res = out.peek();
//out.pop();
return res;
}
public boolean empty() {
return in.empty()&&out.empty() ? true:false;
}
}
/**
* 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();
*/
225. 用队列实现栈
先直接用了Java的Deque接口实现
没有特殊要求的话栈和队列都可以用Deque<Integer> x = new LinkedList<>();
其中栈的方法主要有push,pop,peek,empty,队列的方法可以看下图
class MyStack {
Deque<Integer> store;
public MyStack() {
store = new LinkedList<>();
}
public void push(int x) {
store.addFirst(x);
}
public int pop() {
return store.removeFirst();
}
public int top() {
return store.getFirst();
}
public boolean empty() {
return store.size() == 0;
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/
下面按照题目要求使用只能先入先出后入后出的Queue
offer向队尾插入,poll弹出队头
模拟入栈后发现出栈时没办法弹出队尾来实现,只能先把前面的元素都出队后才能弹出该元素
所以使用辅助队列来接收前面的元素
class MyStack {
private Queue<Integer> q;
private Queue<Integer> qq;
public MyStack() {
q = new LinkedList<>();
qq = new LinkedList<>();
}
public void push(int x) {
q.offer(x);
}
public int pop() {
while(q.size()>1) qq.offer(q.poll());
int res = q.poll();
Queue<Integer> tmp = q;
q = qq;
qq = tmp;
return res;
}
public int top() {
while(q.size()>1) qq.offer(q.poll());
int res = q.peek();
qq.offer(q.poll());
Queue<Integer> tmp = q;
q = qq;
qq = tmp;
return res;
}
public boolean empty() {
return q.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/
20. 有效的括号
经典用栈处理括号匹配的问题,虽然但是中缀表达式什么的没考,就直接处理三种括号不匹配的情况(左括号更多,右括号更多,左右不一样)就好了
class Solution {
public boolean isValid(String s) {
Deque<Character> stack = new LinkedList<>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') stack.push(')');
else if (s.charAt(i) == '[') stack.push(']');
else if (s.charAt(i) == '{') stack.push('}');
else {
if (!stack.isEmpty() && stack.peek() == s.charAt(i)) stack.pop();
else return false;
}
}
if (stack.isEmpty()) return true;
else return false;
}
}