Stack and queue force deduction problem opening brush

Posted by glenelkins on Fri, 11 Feb 2022 10:14:14 +0100

Question 1: Force deduction 232 questions

Problem solving ideas:

This is related to the characteristics of stacks and queues. As we all know, stacks meet the requirements of "first in and last out", while queues meet the requirements of "first in and first out", so smart humans think of using two stacks to realize queues. Hahaha, smart!!!

The code is as follows:

class MyQueue {
    Stack<Integer> stackIn;
    Stack<Integer> stackOut;
    //Parameterless construction, initialization
    public MyQueue() {
        stackIn = new Stack<>();
        stackOut = new Stack<>();
    }
    //Queue implementation push is the same as stack
    public void push(int x) {
        stackIn.push(x);
    }
    //The queue pop-up needs to pop up the first part of the stack, so first judge whether the stackOut is empty, and then put all stackIn in reverse order until stackIn
    //If it is also empty, it means that it all pops up. Finally, it returns to the top of stackOut
    public int pop() {
        if(stackOut.isEmpty()) {
            while(!stackIn.isEmpty()) {
                stackOut.push(stackIn.pop());
            }  
        }
        return stackOut.pop();
    }
    //Peek is actually similar to pop. It also needs to fill the stackOut completely. After that, peek is at the top of the out
    public int peek() {
        if(stackOut.isEmpty()) {
            while(!stackIn.isEmpty()) {
                stackOut.push(stackIn.pop());
            }  
        }
        return stackOut.peek();
    }
    //If both stackIn and stackOut are empty, they are empty
    public boolean empty() {
        return stackIn.isEmpty() && stackOut.isEmpty();
    }
}

Question 2: Force deduction 225 questions

Basic knowledge see Document I

Problem solving ideas:

Idea 1: two queues (one for storage and the other for assistance) realize stack

Idea 2: a queue (Deque) implementation stack

The code is as follows:

//Idea 1: two queues (one for storage and the other for assistance) implement stack
class MyStack {
    Queue<Integer> queue1;
    Queue<Integer> queue2;
    //initialization
    public MyStack() {
        queue1 = new LinkedList<>();
        queue2 = new LinkedList<>();
    }
    //Stack. Load x into queue 2 = = = > load queue 2 in queue 1 = = = > copy all queue 2 to queue 1 for later use
    public void push(int x) {
        queue2.offer(x);
        while(!queue1.isEmpty()) {
            queue2.offer(queue1.poll());
        }
        Queue<Integer> tempQueue;
        tempQueue = queue1;
        queue1 = queue2;
        queue2 = tempQueue;
    }
    //The order of queue 1 is the order in the stack
    public int pop() {
        return queue1.poll();
    }
    //The order of queue 1 is the order in the stack
    public int top() {
        return queue1.peek();
    }
    //The order of queue 1 is the order in the stack
    public boolean empty() {
        return queue1.isEmpty();
    }
}
//Idea 2: a Deque implementation stack
class MyStack {
    Deque<Integer> deque;
    //initialization
    public MyStack() {
        deque = new ArrayDeque<>();
    }
    //Stack pressing
    public void push(int x) {
        deque.addLast(x);
    }
    //deque all but the last element re-enter the queue, return and delete the first one
    public int pop() {
        int size = deque.size();
        size--;
        while(size-- > 0) {
            deque.addLast(deque.pollFirst());
        }
        int res = deque.pollFirst();
        return res;
    }
    //Returns the last element pushed in by deque
    public int top() {
        return deque.peekLast();
    }
    //Returns whether deque is empty
    public boolean empty() {
        return deque.isEmpty();
    }

Question 3: Force deduction 20 questions

Problem solving ideas:

In case of such pairwise problems, that is, matching problems, it is very appropriate to use stack to solve them!
Matching parentheses have Three cases:
The first case: the string has been traversed, but the stack is not empty, indicating that there are corresponding left parentheses and no right parentheses to match, so return false

The second case: during the process of traversing the string matching, it is found that there are no characters to match in the stack. So return false

The third case: in the process of traversing the string matching, the stack is empty and there are no matching characters, indicating that the corresponding left bracket is not found in the right bracket. return false

The code is as follows:

        Stack<Character> stack = new Stack<>();
        char c;
        for(int i = 0; i < s.length(); i++) {
            c = s.charAt(i);
            if(c == '(') {
                stack.push(')');
            } else if(c == '[') {
                stack.push(']');
            } else if(c == '{') {
                stack.push('}');
            //Case 3: stack Isempty() indicates that there is no matching left bracket for the right bracket
            //Case 2: stack peek() !=  C means there are no matching characters in the stack
            } else if(stack.isEmpty() || stack.peek() != c) {
                return false;
            } else {
                stack.pop();
            }
        }
        //Case 1: the string has been traversed, but the stack is not empty, indicating that there is no matching right bracket in the left bracket
        return stack.isEmpty();

But after writing this, I found that other people's solutions to the problem. Although their ideas are similar, it is also a kind of learning to learn from others. The codes of others are as follows:

        Deque<Character> deque = new LinkedList<>();
        char ch;
        for (int i = 0; i < s.length(); i++) {
            ch = s.charAt(i);
            //When you encounter the left bracket, put the corresponding right bracket on the stack
            if (ch == '(') {
                deque.push(')');
            }else if (ch == '{') {
                deque.push('}');
            }else if (ch == '[') {
                deque.push(']');
            } else if (deque.isEmpty() || deque.peek() != ch) {
                return false;
            }else {//If it is a right parenthesis, judge whether it matches the top element of the stack
                deque.pop();
            }
        }
        //Finally, determine whether the elements in the stack match
        return deque.isEmpty();

At first, I didn't understand very well, so I checked and searched and referred to it This article It can be seen at a glance, hahaha!!!
It is written that both stack and queue can be implemented with deque, which is a double ended queue. It also introduces the comparison of their methods. Here, when deque is used as a stack, its Peek () method is the same as the Peek () method of stack, and it comes out of the stack from the place where it is put into the stack. So use deque peek() != There's nothing wrong with Ch.

Question 4: Force deduction 1047 questions

Problem solving ideas:

It is also a matching problem. You can put the string order into a stack, and then pop up the stack if it is the same, so that the remaining elements in the stack are adjacent and different elements.

The code is as follows:

class Solution {
    public String removeDuplicates(String s) {
        //Dual end queue implementation stack
        Deque<Character> deque = new ArrayDeque<>();
        char c;
        for(int i = 0; i < s.length(); i++) {
            //Take out each character
            c = s.charAt(i);
            //If the stack is empty or the top of the stack is different from the character, press it into the stack; Otherwise, pop up
            if(deque.isEmpty() || c != deque.peek()) {
                deque.push(c);
            } else {
                deque.pop();
            }
        }
        String str = "";
        //Splice into string
        while(!deque.isEmpty()) {
            str = deque.pop() + str;
        }
        return str;
    }
}

Topics: Algorithm leetcode