0
点赞
收藏
分享

微信扫一扫

剑指Offer【刷题笔记31-40题】

扬帆远航_df7c 2022-03-12 阅读 30

31. 栈的压入、弹出序列

31. 栈的压入、弹出序列

思路:

在这里插入图片描述

时间复杂度:O(n)

核心代码:

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

带main函数测试样例:

#include <iostream>
#include <vector>
#include <stack>

using namespace std;

bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
    if (pushed.empty() && pushed.empty()) return true;
    if (pushed.size() != popped.size()) return false;
    int i = 0;
    stack<int> stk;
    for (int x : pushed) {
        stk.push(x);
        while (stk.size() && stk.top() == popped[i]) {
            i++;
            stk.pop();
        }
    }
    return stk.empty();
}

int main() {
    vector<int> pushed = {1, 2, 3, 4, 5};
    vector<int> popped = {4, 5, 3, 2, 1};
    cout << validateStackSequences(pushed, popped) << endl;
    return 0;
}
举报

相关推荐

0 条评论