栈和队列
栈 LIFO 后入先出
队列 FIFO 先进先出
Collections 中可由Queue完成,Queue的实现类有
- -> Deque -> ArrayDeque
-> LinkedList - ->PriorityQueue
###232. 用栈实现队列
用两个栈可以完成一个队列
一个栈负责进,一个栈负责出
如果stackOut
为空,那么就按顺序弹出stackIn
,放入stackOut
class MyQueue {
Stack<Integer> stackIn;
Stack<Integer> stackOut;
public MyQueue() {
stackIn = new Stack<>(); // 负责进栈
stackOut = new Stack<>(); // 负责出栈
}
/** Push element x to the back of queue. */
public void push(int x) {
stackIn.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
dumpstackIn();
return stackOut.pop();
}
/** Get the front element. */
public int peek() {
dumpstackIn();
return stackOut.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return stackIn.isEmpty() && stackOut.isEmpty();
}
// 如果stackOut为空,那么将stackIn中的元素全部放到stackOut中
private void dumpstackIn(){
if (!stackOut.isEmpty()) return;
while (!stackIn.isEmpty()){
stackOut.push(stackIn.pop());
}
}
}
###225. 用队列实现栈
用一个队列实现栈
- 每次
push
都放入一个进入队列,此时,除了队尾的(新进入的)以外,全部弹出再进入。
class MyStack {
Queue<Integer> queue;
public MyStack() {
queue = new LinkedList<>();
}
public void push(int x) {
queue.offer(x);
int size = queue.size();
//移动除了 A 的其它数
while (size-- > 1)
queue.offer(queue.poll());
}
public int pop() {
return queue.poll();
}
public int top() {
return queue.peek();
}
public boolean empty() {
return queue.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> deque =new ArrayDeque<>();
Map<Character,Character> map = new HashMap<>();
map.put('(',')');
map.put('{','}');
map.put('[',']');
char[] str = s.toCharArray();
for(Character c : str){
if(c == '(' || c == '[' || c=='{'){
deque.offerLast(c);
}else{
if (deque.isEmpty() || map.getOrDefault(deque.peekLast(), '\0') != c) {
return false;
}
if(map.get(deque.peekLast()).equals(c)){
deque.pollLast();
}
}
}
return deque.isEmpty();
}
}
1047. 删除字符串中的所有相邻重复项
class Solution {
public String removeDuplicates(String s) {
char[] str = s.toCharArray();
Deque<Character> deque = new ArrayDeque<>();
for(Character c : str){
if(deque.peekLast() == c){
deque.pollLast();
continue;
}else{
deque.offerLast(c);
}
}
return deque.toString().replace("[", "").replace(", ", "").replace("]", "");
}
}