What classic problems can stacks and queues solve? Every question can be found on my homepage, welcome everyone to pay attention~~
(1) Bracket matching problem (stack)
(2) String deduplication problem (stack)
(3) Reverse Polish expression problem (stack)
(4) Sliding window maximum problem (monotonic queue)
(5) Top K elements with the most occurrences (priority queue)
(6) Stack implementation queue
(7) Queue implementation stack
1. Solution
Given a string that contains only '('
, ')'
, '{'
, '}'
, '['
, determine whether the string is valid.']'
s
A valid string must satisfy:
- An opening parenthesis must be closed with a closing parenthesis of the same type.
- Opening parentheses must be closed in the correct order.
- Each closing parenthesis has a corresponding opening parenthesis of the same type
class MyQueue {
Stack<Integer> stack1;
Stack<Integer> stack2;
public MyQueue() {
stack1=new Stack<>();
stack2=new Stack<>();
}
public void push(int x) {
stack1.push(x);
}
public int pop() {
if(!stack2.isEmpty()){
return stack2.pop();
}
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
return stack2.pop();
}
public int peek() {
if(!stack2.isEmpty()){
return stack2.peek();
}
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
return stack2.peek();
}
public boolean empty() {
return stack1.isEmpty()&&stack2.isEmpty();
}
}
2. Basic knowledge of the stack
The most notable feature of the stack is: first in last out
1. Common implementation classes of stacks in Java:
The most basic implementation: Stack<Integer> stack=new Stack<>();
Double-ended queue implementation: Deque<Integer> stack=new LinkedList<>();
2. Common methods of stack
push(x) -- push an element to the tail of the queue.
pop() -- removes an element from the head of the queue.
peek() -- returns the element at the head of the queue.
empty() -- returns whether the queue is empty.
3. Basic knowledge of queues
The most notable feature of the queue is: first in first out
1. Common implementation classes of queues in Java:
Ordinary queue: Queue<Integer> queue=new LinkedList<>();
Double-ended queue: Deque<Integer> queue=new LinkedList<>();
Priority queue: PriorityQueue<Integer> queue=new PriorityQueue<>();
2. Common methods of queues
add Add an element If the queue is full, throw a IIIegaISlabEepeplian exception
remove Remove and return the element at the head of the queue If the queue is empty, throw a NoSuchElementException
element Return the element at the head of the queue If the queue is empty, then Throws a NoSuchElementException
size The number of elements
offer Add an element and return true If the queue is full, return false
poll Remove and return the element at the head of the queue If the queue is empty, return null
peek Return the element at the head of the queue If the queue is empty, return null
put adds an element, blocks if the queue is full
take removes and returns the element at the head of the queue, blocks if the queue is empty