剑指 Offer 31-栈的压入、弹出序列c++

----------------------2020/12/28二刷------------------------------

//每次入栈一次再判断能否连续出栈
class Solution {
public:
    bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
        stack<int> s;
        int pIndex = 0;
        for(int nums : pushed) {
            s.push(nums);
            while(!s.empty() && s.top() == popped[pIndex]) {
                s.pop();
                pIndex++;
            }
        }
        return s.empty();
    }
};

-----------------------------------一刷--------------------------------

题目描述

在这里插入图片描述

解法 模拟

模拟出栈入栈过程
法一、先入栈再连续出栈

class Solution {
public:
    bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
        stack <int> s;
        int len1 = pushed.size();
        int len2 = popped.size();
        for( int i = 0,j=0 ; i < len1; i++) {
            s.push(pushed[i]);
            while(!s.empty() && j < len2 && s.top() == popped[j]) {
                s.pop();
                j++;
            }
        }
        return s.empty();
        
    }
};

在这里插入图片描述
法二、
先连续入栈再判断出栈

class Solution {
public:
    bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
        stack <int> s;
        if(pushed.size() == 0) return true;
        s.push(pushed[0]);
        int Iindex = 1;
        int Oindex = 0;
        int len1 = pushed.size() - 1;
        int len2 = popped.size() - 1;
        
        while(Oindex <= len2) {
            while(s.empty() || s.top() != popped[Oindex] && Iindex <= len1) {
            //判断empty是因为可能栈在过程中会清空,这时候就得先入栈一个。
                s.push(pushed[Iindex]);
                Iindex++;
            }
            if(s.top() != popped[Oindex]) return false;
            s.pop();
            Oindex++;
        }
        return s.empty();
        
    }
};

法二写得不是很好。。。但是思想是没问题的,有空回来改改
在这里插入图片描述
两者的时间复杂度都是O(n) 空间复杂度O(n)

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值