Data structure refresher: Day 9

Table of contents

1. Valid parentheses

 1. Stack

Complexity analysis

2. Use stack to implement queue

 1. Dual stack

Complexity analysis

1. Valid parentheses

20. Valid parentheses - LeetCode https://leetcode.cn/problems/valid-parentheses/?plan=data-structures&plan_progress=ggfacv7

 1. Stack

Determining the validity of parentheses can be solved using the data structure "stack".

We iterate over the given string ss. When we encounter an opening parenthesis, we expect a closing parenthesis of the same type to close it during subsequent traversals. Since the left bracket encountered later must be closed first, we can put this left bracket on the top of the stack.

When we encounter a right parenthesis, we need to close a left parenthesis of the same type. At this point, we can take out the left bracket at the top of the stack and determine whether they are the same type of brackets. If they are not of the same type, or there is no left parenthesis on the stack, then the string s is invalid and False is returned. In order to quickly determine the type of brackets, we can use a hash table to store each bracket. The key of the hash table is the right bracket and the value is the left bracket of the same type.

After the traversal is completed, if there is no left bracket in the stack, it means that we have closed all the left brackets in the string s and return True, otherwise it returns False.

Note that the length of a valid string must be an even number, so if the length of the string is an odd number, we can directly return False, eliminating the subsequent traversal judgment process.

class Solution {
public:
    bool isValid(string s) {
        int n = s.size();
        if (n % 2 == 1) {
            return false;
        }

        unordered_map<char, char> pairs = {
            {')', '('},
            {']', '['},
            {'}', '{'}
        };
        stack<char> stk;
        for (char ch: s) {
            if (pairs.count(ch)) {
                if (stk.empty() || stk.top() != pairs[ch]) {
                    return false;
                }
                stk.pop();
            }
            else {
                stk.push(ch);
            }
        }
        return stk.empty();
    }
};

Complexity analysis

Time complexity: O(n), where n is the length of string s.

Space complexity: O(n+∣Σ∣), where Σ represents the character set. The string in this question only contains 6 types of brackets, ∣Σ∣=6. The number of characters in the stack is O(n), and the space used by the hash table is O(∣Σ∣). The total space complexity can be obtained by adding them together.

2. Use stack to implement queue

232. Implement queue using stack - LeetCode https://leetcode.cn/problems/implement-queue-using-stacks/

 1. Dual stack

Ideas

One stack is used as an input stack for pushing incoming data; the other stack is used as an output stack for pop and peek operations.

Each time a pop or peek occurs, if the output stack is empty, all the data in the input stack will be popped out and pushed into the output stack in sequence. In this way, the order of the output stack from the top to the bottom of the stack is the order of the queue from the beginning to the end of the queue.

class MyQueue {
private:
    stack<int> inStack, outStack;

    void in2out() {
        while (!inStack.empty()) {
            outStack.push(inStack.top());
            inStack.pop();
        }
    }

public:
    MyQueue() {}

    void push(int x) {
        inStack.push(x);
    }

    int pop() {
        if (outStack.empty()) {
            in2out();
        }
        int x = outStack.top();
        outStack.pop();
        return x;
    }

    int peek() {
        if (outStack.empty()) {
            in2out();
        }
        return outStack.top();
    }

    bool empty() {
        return inStack.empty() && outStack.empty();
    }
};

Complexity analysis

Time complexity: push and empty are O(1), pop and peek are amortized O(1). For each element, there are at most two pushes and two pops from the stack, so the amortized complexity is O(1).

Space complexity: O(n). where n is the total number of operations. For the case of n push operations, there will be n elements in the queue, so the space complexity is O(n).

Guess you like

Origin blog.csdn.net/m0_63309778/article/details/126743818