leetcode解题栈与列队篇

本文介绍了如何使用栈和队列实现特定功能,如用两个栈模拟队列,用队列实现栈,以及在有效括号验证、删除字符串重复项、逆波兰表达式求值和滑动窗口最大值等经典问题中的应用。通过这些实例,展示了栈和队列在算法设计中的重要性和灵活性。
摘要由CSDN通过智能技术生成

栈与队列

1. 232.用栈实现队列

请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):

实现 MyQueue 类:

void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-queue-using-stacks
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class MyQueue {
public:
    MyQueue() {

    }
    
    void push(int x) {
        stackIn.push(x);
    }
    
    int pop() {
        int result;
        if(stackOut.empty()){
            while(!stackIn.empty()){
                stackOut.push(stackIn.top());
                stackIn.pop();
            }
        }
        result = stackOut.top();
        stackOut.pop();
        
        return result;
    }
    
    int peek() {
        int result;
        if(stackOut.empty()){
            while(!stackIn.empty()){
                stackOut.push(stackIn.top());
                stackIn.pop();
            }
        }
        result = stackOut.top();
        return result;
    }
    
    bool empty() {
        return stackOut.empty() && stackIn.empty();
    }
private:
    stack<int> stackIn;
    stack<int> stackOut;
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue* obj = new MyQueue();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->peek();
 * bool param_4 = obj->empty();
 */

用了两个stack,分为入栈和出栈,入栈处理push操作,当需要pop\top的时候,将入栈的元素全部导入出栈,然后从出栈弹出元素,就实现了队列的弹出操作,empty( )操作判断二者皆为空即可。

2. 225. 用队列实现栈

请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(pushtoppopempty)。

class MyStack {
public:
    MyStack() {

    }
    
    void push(int x) {
        queue.push(x);
    }
    
    int pop() {
        vector<int> tmp;
        while(!queue.empty()){
            tmp.push_back(queue.front());
            queue.pop();
        }
        for(int i = 0 ; i < tmp.size() - 1;i++){
            queue.push(tmp[i]);
        }
        return tmp[tmp.size() - 1];
    }
    
    int top() {
        vector<int> tmp;
        while(!queue.empty()){
            tmp.push_back(queue.front());
            queue.pop();
        }
        for(int t : tmp){
            queue.push(t);
        }
        return tmp[tmp.size() - 1];
    }
    
    bool empty() {
        return queue.empty();
    }

private:
    queue<int> queue;
};

/**
 * 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();
 */

本题也就是使用了一个队列来实现,但是在top和pop操作的时候使用了额外的存储空间,其余的不难。

3. 20. 有效的括号

给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串 s ,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。

class Solution {
public:
    bool isValid(string s) {
        stack<char> stack;
        for(char c : s){
            if(c == '('  || c == '[' || c == '{'){
                stack.push(c);
            }else{
                if(stack.empty()){
                    return false;
                }else{
                    if(c == ')'){
                        if(stack.top() == '(')
                            stack.pop();
                        else
                            return false;
                    }
                    if(c == ']'){
                        if(stack.top() == '[')
                            stack.pop();
                        else
                            return false;
                    }
                    if(c == '}'){
                        if(stack.top() == '{')
                            stack.pop();
                        else
                            return false;
                    }
                }
            }
        }

        return stack.empty();
    }
};

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();
    }
};

本题使用stack来进行括号匹配,遵循着括号匹配的先进后出的原则,难度不大,注意好各种不匹配的条件就行,方法2使用了unordered_map()来简化了判断操作。

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

给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。

在 S 上反复执行重复项删除操作,直到无法继续删除。

在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-all-adjacent-duplicates-in-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution {
public:
    string removeDuplicates(string s) {
        stack<char> stack;

        for(char c : s){
            if(stack.empty()){
                stack.push(c);
            }else{
                if(stack.top() == c){
                    stack.pop();
                }else{
                    stack.push(c);
                }
            }
        }

        string result;
        result.resize(stack.size());
        int count = stack.size() - 1;
        while(!stack.empty()){
            result[count--] = stack.top();
            stack.pop();
        }
        return result;
    }
};

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;
    }
};

同样是利用栈的思想,判断下一个字符串与栈顶的元素是否能消除,有一个更简单的做法是直接利用string做为char的栈,然后使用push_backpop_back进行出入栈,减少了空间开销。

5. 150. 逆波兰表达式求值

根据 逆波兰表示法,求表达式的值。

有效的算符包括 +、-、*、/ 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。

注意 两个整数之间的除法只保留整数部分。

可以保证给定的逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/evaluate-reverse-polish-notation
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution {
public:
    int evalRPN(vector<string>& tokens) {

        stack<int> stack;
        for(string s : tokens){
            if(s == "+"){
                int n2 = stack.top();
                stack.pop();
                int n1 = stack.top();
                stack.pop();
                stack.push(n1 + n2);
            }else if(s == "-"){
                int n2 = stack.top();
                stack.pop();
                int n1 = stack.top();
                stack.pop();
                stack.push(n1 - n2);
            }else if(s == "*"){
                int n2 = stack.top();
                stack.pop();
                int n1 = stack.top();
                stack.pop();
                stack.push(n1 * n2);
            }else if(s == "/"){
                int n2 = stack.top();
                stack.pop();
                int n1 = stack.top();
                stack.pop();
                stack.push(n1 / n2);
            }else{
                stack.push(stoi(s));
            }
        }
        return stack.top();

    }
};

后续表达式,按照栈的做法来做很简单。主要是考察对后续表达式的掌握程度

6. 239. 滑动窗口最大值

给你一个整数数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。

返回 滑动窗口中的最大值 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sliding-window-maximum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution {
public:
    // 优先队列
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        priority_queue<pair<int,int>> priority_queue;
        vector<int> result;
        for(int i = 0 ; i < k ; i++){
            priority_queue.emplace(nums[i],i);
        }
        result.push_back(priority_queue.top().first); 

        for(int i = k ; i < nums.size() ; i++){
            priority_queue.emplace(nums[i],i);
            while(priority_queue.top().second < i - k + 1){
                priority_queue.pop();
            }
            result.push_back(priority_queue.top().first);
        }
        return result;

    }
};

对于「最大值」,我们可以想到一种非常合适的数据结构,那就是优先队列(堆),其中的大根堆可以帮助我们实时维护一系列元素中的最大值。

对于本题而言,初始时,我们将数组
nums 的前k 个元素放入优先队列中。每当我们向右移动窗口时,我们就可以把一个新的元素放入优先队列中,此时堆顶的元素就是堆中所有元素的最大值。然而这个最大值可能并不在滑动窗口中,在这种情况下,这个值在数组nums 中的位置出现在滑动窗口左边界的左侧。因此,当我们后续继续向右移动窗口时,这个值就永远不可能出现在滑动窗口中了,我们可以将其永久地从优先队列中移除。

我们不断地移除堆顶的元素,直到其确实出现在滑动窗口中。此时,堆顶元素就是滑动窗口中的最大值。为了方便判断堆顶元素与滑动窗口的位置关系,我们可以在优先队列中存储二元组
(num,index),表示元素num 在数组中的下标为index。

使用了优先队列,但是在更新队列的时候不着急将过期的元素删除,而是等到要用的时候再进行判断,原本我的思路之一也是自己实现一个队列结构,然后通过复杂点的操作将优先队列中过期的元素删除。

还有一种做法是单调队列。

7. 347.前 K 个高频元素

给你一个整数数组 nums和一个整数 k ,请你返回其中出现频率前 k高的元素。你可以按 任意顺序返回答案。

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        //思路:将频率用map统计,再统统放到优先队列中
        unordered_map<int,int> map;
        priority_queue<pair<int,int>> queue;
        vector<int> result;
        for(int i : nums){
            map[i]++;
        }
        for(auto m : map){
            queue.emplace(m.second,m.first);
        }

        for(int i = 0 ; i < k ; i++){
            result.push_back(queue.top().second);
            queue.pop();
        }
        return result;
    }
};

在优先队列中放元组类型的话,默认会按照pair的第一个数进行排序,且是降序排列。

其实就是一个披着队列外衣的堆,因为优先级队列对外接口只是从队头取元素,从队尾添加元素,再无其他取元素的方式,看起来就是一个队列。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值