代码随想录训练营第十天|栈与队列理论基础、 232.用栈实现队列 、 225. 用队列实现栈 、 20. 有效的括号 、1047. 删除字符串中的所有相邻重复项

一、栈和队列理论基础

文章讲解: 代码随想录

栈和队列是STL(C++标准库)里面的两个数据结构

栈:先进后出

1.C++中stack 是容器么?  

STL中栈往往不被归类为容器,而被归类为container adapter(容器适配器)

2.我们使用的stack是属于哪个版本的STL?

常用的SGI STL,如果没有指定底层实现的话,默认是以deque为缺省情况下栈的底层结构。

deque是一个双向队列,只要封住一段,只开通另一端就可以实现栈的逻辑了。

3.stack 提供迭代器来遍历stack空间么?

栈提供push 和 pop 等等接口,所有元素必须符合先进后出规则,所以栈不提供走访功能,也不提供迭代器(iterator)

4.栈是以底层容器完成其所有的工作,对外提供统一的接口,底层容器是可插拔的(也就是说我们可以控制使用哪种容器来实现栈的功能)。

栈的内部结构,栈的底层实现可以是vector,deque,list 都是可以的, 主要就是数组和链表的底层实现。

pop(),top(),push(),empty()

队列:先进先出

1.STL 队列也不被归类为容器,而被归类为container adapter( 容器适配器)。

2.SGI STL中 队列底层实现缺省情况下一样使用deque实现的。

3.队列中先进先出的数据结构,同样不允许有遍历行为,不提供迭代器, SGI STL中队列一样是以deque为缺省情况下的底部结构。

pop(),front(),back(),push(),empty()

二、用栈实现队列

题目链接/文章讲解/视频讲解: 代码随想录

1.本题逻辑不难,两个栈实现队列

2.细节:①要在栈st2为空的情况下才插入元素,这样不会满足先进先出的原则,导致后来push的元素先出了

               ②peek()函数可以复用pop()函数

3.报错eference binding to misaligned address 0xbebebebebebec0ba for type ‘int‘, which requir 4

两种可能,数组越界或栈stack<int> stk;为空时访问了stk.top()

代码

class MyQueue {
private:
 stack<int> st1;
 stack<int> st2;
public:
    MyQueue() {
        
    }
    void push(int x) {
        st1.push(x);
    }
    int pop() {
        if(st2.empty())
        {
        while(!st1.empty())
        {
            st2.push(st1.top());
            st1.pop();
        }
        }
        int result=st2.top();
        st2.pop();
        return result;
    }   
    int peek() 
    {
        int res = this->pop(); // 直接使用已有的pop函数
        st2.push(res); // 因为pop函数弹出了元素res,所以再添加回去
        return res;
    }
    bool empty() {
        if(st1.empty()&&st2.empty())
        {
            return true;
        }
        else return false;
    }
};

三、用队列实现栈 

题目链接/文章讲解/视频讲解: 代码随想录

方法一:1.一个队列进行辅助储存(过渡),主要在q1 

代码:top为q1.back()

class MyStack {
public:

    queue<int> q1; 
    queue<int> q2; 
    MyStack() {

    }
    
    void push(int x) {
        q1.push(x);
    }
    
    int pop() {
        int result=q1.back();
        int count=0;
        while(!q1.empty())
        {
            q2.push(q1.front());
            q1.pop();
            count++;
        }
        while(count>1)
        {   q1.push(q2.front());
            q2.pop();
            count--;
        }
        while (!q2.empty()) { 
            q2.pop();
        }
        return result;
    }
    
    int top() {
        return q1.back();
    }
    
    bool empty() {
         return q1.empty();
    }
};

代码:top为q1.front() 

 int pop() {
        int size = que1.size();
        size--;
        while (size--) { // 将que1 导入que2,但要留下最后一个元素
            que2.push(que1.front());
            que1.pop();
        }

        int result = que1.front(); // 留下的最后一个元素就是要返回的值
        que1.pop();
        que1 = que2;            // 再将que2赋值给que1
        while (!que2.empty()) { // 清空que2
            que2.pop();
        }
        return result;
    }

    /** Get the top element.
     ** Can not use back() direactly.
     */
    int top(){
        int size = que1.size();
        size--;
        while (size--){
            // 将que1 导入que2,但要留下最后一个元素
            que2.push(que1.front());
            que1.pop();
        }

        int result = que1.front(); // 留下的最后一个元素就是要回返的值
        que2.push(que1.front());   // 获取值后将最后一个元素也加入que2中,保持原本的结构不变
        que1.pop();

        que1 = que2; // 再将que2赋值给que1
        while (!que2.empty()){
            // 清空que2
            que2.pop();
        }
        return result;
    }

方法二: 一个队列

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

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.
     ** Can not use back() direactly.
     */
    int top(){
        int size = que.size();
        size--;
        while (size--){
            // 将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部
            que.push(que.front());
            que.pop();
        }
        int result = que.front(); // 此时获得的元素就是栈顶的元素了
        que.push(que.front());    // 将获取完的元素也重新添加到队列尾部,保证数据结构没有变化
        que.pop();
        return result;
    }

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

四、有效的括号 

题目链接/文章讲解/视频讲解: 代码随想录

1.匹配问题用栈(先进后出)

代码:

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

 代码:好妙,目前水平达不到

先入左括号(把左括号转换为右括号),遇到右括号再进行判断,如果没有插入,说明是字符串第一个是右括号(false),插入的和前一个不匹配(false),匹配则pop(),最后再empty(),非空说明左括号多了,空表示全部匹配上了

class Solution {
public:
    bool isValid(string s) {
        if (s.size() % 2 != 0) return false; // 如果s的长度为奇数,一定不符合要求
        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(']');
            // 第三种情况:遍历字符串匹配的过程中,栈已经为空了,没有匹配的字符了,说明右括号没有找到对应的左括号 return false
            // 第二种情况:遍历字符串匹配的过程中,发现栈里没有我们要匹配的字符。所以return false
            else if (st.empty() || st.top() != s[i]) return false;
            else st.pop(); // st.top() 与 s[i]相等,栈弹出元素
        }
        // 第一种情况:此时我们已经遍历完了字符串,但是栈不为空,说明有相应的左括号没有右括号来匹配,所以return false,否则就return true
        return st.empty();
    }
};

五、删除字符串中的所有相邻重复项 

题目链接/文章讲解/视频讲解: 代码随想录

1. 栈为什么适合做这种类似于爱消除的操作,因为栈帮助我们记录了遍历数组当前元素时候,前一个元素是什么。

通过栈顶的返回记录了前一个元素是什么,所以适合做匹配问题

2.最后栈是先进后出的,所以要进行一个反转的操作

代码:

class Solution {
public:
    string removeDuplicates(string s) {
    stack<char> st;
    for(int i=0;i<s.size();i++)
    {
        if(st.empty())
        {
        st.push(s[i]);
        
        }
        else if(st.top()==s[i])
        {
            st.pop();
           
        }
        else 
        {
            st.push(s[i]);
            
        }
    }
    string result;
    while(!st.empty())
    {
        result+=st.top();
        st.pop();
    }
    reverse(result.begin(),result.end());
    return result;
    }
};

这两个push(s)可以放到一项中

for (char s : S) {
            if (st.empty() || s != st.top()) {
                st.push(s);
            } else {
                st.pop(); // s 与 st.top()相等的情况
            }
        }

第二十二天的算法训练营主要涵盖了Leetcode题目的三道题目,分别是Leetcode 28 "Find the Index of the First Occurrence in a String",Leetcode 977 "有序数组的平方",和Leetcode 209 "长度最小的子数组"。 首先是Leetcode 28题,题目要求在给定的字符串找到第一个出现的字符的索引。思路是使用双指针来遍历字符串,一个指向字符串的开头,另一个指向字符串的结尾。通过比较两个指针所指向的字符是否相等来判断是否找到了第一个出现的字符。具体实现代码如下: ```python def findIndex(self, s: str) -> int: left = 0 right = len(s) - 1 while left <= right: if s[left == s[right]: return left left += 1 right -= 1 return -1 ``` 接下来是Leetcode 977题,题目要求对给定的有序数组的元素进行平方,并按照非递减的顺序返回结果。这里由于数组已经是有序的,所以可以使用双指针的方法来解决问题。一个指针指向数组的开头,另一个指针指向数组的末尾。通过比较两个指针所指向的元素的绝对值的大小来确定哪个元素的平方应该放在结果数组的末尾。具体实现代码如下: ```python def sortedSquares(self, nums: List[int]) -> List[int]: left = 0 right = len(nums) - 1 ans = [] while left <= right: if abs(nums[left]) >= abs(nums[right]): ans.append(nums[left ** 2) left += 1 else: ans.append(nums[right ** 2) right -= 1 return ans[::-1] ``` 最后是Leetcode 209题,题目要求在给定的数组找到长度最小的子数组,使得子数组的和大于等于给定的目标值。这里可以使用滑动窗口的方法来解决问题。使用两个指针来表示滑动窗口的左边界和右边界,通过移动指针来调整滑动窗口的大小,使得滑动窗口的元素的和满足题目要求。具体实现代码如下: ```python def minSubArrayLen(self, target: int, nums: List[int]) -> int: left = 0 right = 0 ans = float('inf') total = 0 while right < len(nums): total += nums[right] while total >= target: ans = min(ans, right - left + 1) total -= nums[left] left += 1 right += 1 return ans if ans != float('inf') else 0 ``` 以上就是第二十二天的算法训练营的内容。通过这些题目的练习,可以提升对双指针和滑动窗口等算法的理解和应用能力。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值