栈与队列--Leetcode刷刷刷

来自代码随想录的刷题路线:代码随想录

栈与队列:

232.用栈实现队列

img

思路:

栈的基本操作:

img

img

在push数据的时候,只要数据放进输入栈就好,但在pop的时候,操作就复杂一些,输出栈如果为空,就把进栈数据全部导入进来(注意是全部导入),再从出栈弹出数据,如果输出栈不为空,则直接从出栈弹出数据就可以了。

最后如何判断队列为空呢?如果进栈和出栈都为空的话,说明模拟的队列为空了。

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) {
        stIn.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        // 只有当stOut为空的时候,再从stIn里导入数据(导入stIn全部数据)
        if (stOut.empty()) {
            // 从stIn导入数据直到stIn为空
            while(!stIn.empty()) {
                stOut.push(stIn.top());
                stIn.pop();
            }
        }
        int result = stOut.top();
        stOut.pop();
        return result;
    }

    /** Get the front element. */
    int peek() {
        int res = this->pop(); // 直接使用已有的pop函数
        stOut.push(res); // 因为pop函数弹出了元素res,所以再添加回去
        return res;
    }

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

225.用队列实现栈

img

思路:

img

  1. 定义空与非空两个队列,每次pop或者top前先确定哪个是非空。
  2. pop就是先把非空队列的前n个元素放到空队列里,再移除并返回最后一个元素。再更新空与非空
  3. top就是在pop的基础上,把移除的元素再push进非空队列中
class MyStack {
public:
    queue<int> notNull;
    queue<int> isNull;
    MyStack() {

    }
    
    //判断 更新哪个空队列
    void JudgeEmpty(){
        if(notNull.empty() && isNull.empty()){
            return;
        }
        if(notNull.empty()){
            swap(isNull, notNull);
        }
    }

    //将元素 x 压入栈顶
    void push(int x) {
        this->JudgeEmpty();
        notNull.push(x);
    }
    
    //移除并返回栈顶元素
    int pop() {
        this->JudgeEmpty();

        //先把前num个元素送到空队列中 再把最后一个元素移除并返回
        int num = notNull.size() - 1;
        if(num < 0){
            return -1;
        }

        while(num--){
            isNull.push(notNull.front());
            notNull.pop();
        }
        int result = notNull.front();
        notNull.pop();

        //更新空与非空队列
        swap(isNull, notNull);

        return result;
    }
    
    //返回栈顶元素
    int top() {
        return notNull.back();	//最后一个元素
    }
    
    bool empty() {
        return isNull.empty() && notNull.empty();
    }
};

/**
 * 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();
 * bool param_4 = obj->empty();
 */

优化

其实这道题目就是用一个队列就够了。

一个队列在模拟栈弹出元素的时候只要将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部,此时再去弹出元素就是栈的顺序了。

class MyStack {
public:
    queue<int> que;
    /** Initialize your data structure here. */
    MyStack() {

    }
    /** Push element x onto stack. */
    void push(int x) {
        que.push(x);
    }
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int size = que.size();
        size--;
        while (size--) { // 将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部
            que.push(que.front());
            que.pop();
        }
        int result = que.front(); // 此时弹出的元素顺序就是栈的顺序了
        que.pop();
        return result;
    }

    /** Get the top element. */
    int top() {
        return que.back();
    }

    /** Returns whether the stack is empty. */
    bool empty() {
        return que.empty();
    }
};
  • 时间复杂度: push为O(n),其他为O(1)
  • 空间复杂度: O(n)

20.有效的括号

imgimg

img

第一种情况:已经遍历完了字符串,但是栈不为空,说明有相应的左括号没有右括号来匹配,所以return false

第二种情况:遍历字符串匹配的过程中,发现栈里没有要匹配的字符。所以return false

第三种情况:遍历字符串匹配的过程中,栈已经为空了,没有匹配的字符了,说明右括号没有找到对应的左括号return false

那么什么时候说明左括号和右括号全都匹配了呢,就是字符串遍历完之后,栈是空的,就说明全都匹配了。

class Solution {
public:
    bool isValid(string s) {
        if(s.size() % 2 == 1) return false;
        stack<char> st;

        for(int i = 0; i < s.size(); i++){
            //遍历到左括号则入栈对应的右括号
            if(s[i] == '(') st.push(')');   
            else if(s[i] == '{') st.push('}');  
            else if(s[i] == '[') st.push(']');  

            //当前字符为右括号但栈内为空则说明没有与其匹配的左括号
            else if(st.empty()) return false;
            //栈顶的字符与当前右括号不相等说明左右括号的闭合顺序不一致
            else if(s[i] != st.top()) return false;

            //遇到与栈顶相同的字符则消除栈顶元素
            else st.pop();
        }
        //当遍历完字符串但栈不为空 说明有左括号没有对应的右括号与其匹配
        if(!st.empty()) return false;
        return true;
    }
};

1047.删除字符串中的所有相邻重复项 img

img

class Solution {
public:
    string removeDuplicates(string S) {
        stack<char> st;
        for (char s : S) {
            if (st.empty() || s != st.top()) {
                st.push(s);
            } else {
                st.pop(); // s 与 st.top()相等的情况
            }
        }
        string result = "";
        while (!st.empty()) { // 将栈中元素放到result字符串汇总
            result += st.top();
            st.pop();
        }
        reverse (result.begin(), result.end()); // 此时字符串需要反转一下
        return result;

    }
};

也可以拿字符串当做栈,空间复杂度为O(1)–返回值不计空间复杂度

class Solution {
public:
    string removeDuplicates(string S) {
        string result;
        for(char s : S) {
            if(result.empty() || result.back() != s) {
                result.push_back(s);
            }
            else {
                result.pop_back();
            }
        }
        return result;
    }
};

150.逆波兰表达式求值

img

img

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        // 力扣修改了后台测试数据,需要用longlong
        stack<long long> st; 
        for (int i = 0; i < tokens.size(); i++) {
            if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") {
                long long num1 = st.top();
                st.pop();
                long long num2 = st.top();
                st.pop();
                if (tokens[i] == "+") st.push(num2 + num1);
                if (tokens[i] == "-") st.push(num2 - num1);
                if (tokens[i] == "*") st.push(num2 * num1);
                if (tokens[i] == "/") st.push(num2 / num1);
            } else {
                st.push(stoll(tokens[i]));
            }
        }

        int result = st.top();
        st.pop(); // 把栈里最后一个元素弹出(其实不弹出也没事)
        return result;
    }
};

239. 滑动窗口最大值

img

img

class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        int left = 0;
        int right = k - 1; 
        vector<int> result;
        while(right < nums.size()){
            int max = nums[left];
            for(int i = left + 1; i <= right; i++){
                if(max < nums[i]){
                    max = nums[i];
                }
            }
            result.push_back(max);
            left++;
            right++;
        }
        return result;
    }
};

单调队列

单调队列是队列中元素之间的关系具有单调性,而且,队首和队尾都可以进行出队操作,只有队尾可以进行入队操作,本质是有双端队列deque实现的。

img

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值