Location>code7788 >text

Code Randomizer Day 10

Popularity:208 ℃/2024-08-09 19:16:48

232.Implementing Queues with Stacks

You are asked to implement a first-in-first-out queue using only two stacks. The queue should support all operations supported by general queues (push, pop, peek, empty):

Implements the MyQueue class:

void push(int x) push element x to the end of the queue
int pop() removes the element from the beginning of the queue and returns it.
int peek() returns the element at the beginning of the queue
boolean empty() Returns true if the queue is empty; otherwise, returns false.
Description:

You can only use standard stack operations -- that is, only push to top, peek/pop from top, size, and is empty are legal.
Your language may not support stacks. You can simulate a stack using a list or a deque (double-ended queue), as long as it's a standard stack operation.

Example 1:

importation:
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
exports:
[null, null, null, 1, 1, false]

account for:
MyQueue myQueue = new MyQueue();
(1); // queue is: [1]
(2); // queue is: [1, 2] (leftmost is front of the queue)
(); // return 1
(); // return 1, queue is [2]
(); // return false

Tip:

1 <= x <= 9
Call push, pop, peek, and empty up to 100 times.
Assuming that all operations are valid (e.g., an empty queue does not call a pop or peek operation)

Advancement:

Can you implement each operation with an equalized time complexity of\(O(1)\) of the queue? In other words, the total time complexity of performing n operations is\(O(n)\) , even though one of these operations may take longer.


Positive solution (simulation)

This is a simulation question that does not involve specific algorithms, and examines the mastery of stacks and queues.
Use a stack to pattern the behavior of the queue, if you just use a stack, it must not work, so you need two stacks an input stack, an output stack, here to pay attention to the relationship between the input stack and the output stack.
In push data, as long as the data into the input stack is good, but in pop, the operation is a little more complex, the output stack if empty, the incoming data into the stack all imported (note that all import); ;)
Then pop the data from the outgoing stack. If the output stack is not empty, then just pop the data directly from the outgoing stack.
Finally, how do you determine that the queue is empty? If both the incoming and outgoing stacks are empty, the simulated queue is empty.
When implementing the code, you will find that the functions pop() and peek() have similar functions and the code implementation is similar, so you can think about how to abstract the code.
动画

Upcode (●'◡'●)
class MyQueue {
public:
    stack<int> stIn;
    stack<int> stOut;
    /** Initialize your data structure here. */
    MyQueue() {

    }
    /** Push element x to the back of queue. */
    void push(int x) {
        (x);
    }

    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        // Only whenstOutWhen empty,retrace one's stepsstInImporting data from(import (data)stInAll data)
        if (()) {
            // through (a gap)stInimport (data)数据直到stInempty
            while(!()) {
                (());
                ();
            }
        }
        int result = ();
        ();
        return result;
    }

    /** Get the front element. */
    int peek() {
        int res = this->pop(); // Directly use the existingpopfunction (math.)
        (res); // on account ofpopfunction (math.)弹出了元素res,So add it back.
        return res;
    }

    /** Returns whether the queue is empty. */
    bool empty() {
        return () && ();
    }
};

225. Stack implementation with queues

You are asked to implement a last-in-first-out (LIFO) stack using only two queues and supporting all four operations of a normal stack (push, top, pop, and empty).

Implements the MyStack class:

void push(int x) Presses element x onto the top of the stack.
int pop() Removes and returns the top stack element.
int top() Returns the top element of the stack.
boolean empty() Returns true if the stack is empty; otherwise, returns false.

Attention:

You can only use the standard operations of a queue -- that is, push to back, peek/pop from front, size, and is empty.
Your language may not support queues. You can simulate a queue using a list or a deque, as long as it is a standard queue operation.

Example:

Input:

["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
exports:
[null, null, null, 2, 2, false]

account for:
MyStack myStack = new MyStack();
(1);
(2);
(); // come (or go) back 2
(); // come (or go) back 2
(); // come (or go) back False

Tip:

1 <= x <= 9
Call push, pop, top, and empty up to 100 times.
Each call to pop and top ensures that the stack is not empty.

Advanced: can you implement a stack with just a queue.

Positive solution (simulation)

Actually, this question is just enough to use a queue.

A queue in the simulation of the stack to pop elements as long as the head of the queue (in addition to the last element) to re-add to the end of the queue, and then go to pop the elements is the order of the stack.

Upcode (●'◡'●)
class MyStack {
public.
    queue<int> que.

    /** Initialize your data structure here. */
    MyStack() {

    }

    /** Push element x onto stack. */
    void push(int x) {
        (x);
    }

    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int size = (); int pop(); int pop(); int pop(); int pop()
        size--; while (size--) { // Remove the element on top of the stack and returns that element.
        while (size--) { // Re-add the elements at the head of the stack (except the last one) to the end of the stack.
            (()); (())
            ();
        }
        int result = (); // The order of the popped elements is now the order of the stack.
        (); } int result = (); // The order of the popped elements is now the order of the stack.
        return result; }
    }

    /** Get the top element.
     ** Can not use back() direactly.
     ** Can not use back() direactly.
    int top(){
        int size = (); int
        int size = (); size--; while (size--){
        while (size--){
            // Re-add the elements at the head of the queue (except for the last one) to the tail of the queue
            (()); (())
            ();
        }
        int result = (); // The obtained element is now the top of the stack.
        (()); // Re-add the fetched element to the end of the queue as well, keeping the structure intact.
        (); return result; // Re-add the fetched element to the end of the queue.
        return result; }
    }

    /** Returns whether the stack is empty. */
    bool empty() {
        return (); }
    }
}; }

20. Effective brackets

Given a string s that includes only '(', ')', '{', '}', '[', ']', determine if the string is valid.

Valid strings need to be satisfied:

The left bracket must be closed with a right bracket of the same type.
The left bracket must be closed in the correct order.
Each right brace has a corresponding left brace of the same type.

Example 1:

Input: s = "()"
Output: true

Example 2:

Input: s = "()[]{}"
Output: true

Example 3:

Input: s = "(]"
Output: false

Tip:

1 <= <= 104
s consists only of parentheses '()[]{}'


Positive solution (stack)

Stacks is a very classic question now
思路
Ideas aren't that hard.
Because of the special characteristics of the stack structure, it is very suitable for solving the symmetric matching class of questions

Upcode (●'◡'●)
class Solution {
public.
    bool isValid(string s) {
        if (() % 2 ! = 0) return false; // If s has an odd length, it must not be valid.
        stack<char> st.
        for (int i = 0; i < (); i++) {
            if (s[i] == '(') (')');
            else if (s[i] == '{') (') ('}');
            else if (s[i] == '[') (']'); else if (s[i] == '[') (']');
            // Third case: while traversing the string to match, the stack is empty and there are no more matches, indicating that the right bracket did not find the corresponding left bracket return false
            // In the second case, the stack is empty and there is no match, so the right bracket did not find the corresponding left bracket. So return false
            else if (() || () ! = s[i]) return false; else (); // () !
            else (); // () is equal to s[i], stack pops element
        }
        // First case: we've traversed the string, but the stack isn't empty, which means there's a corresponding left parenthesis that doesn't have a right parenthesis to match, so return false, otherwise return true
        return ();
    }
}; }

It's not easy to write a blog, so please give me some support 8~!