Loading

leetcode-946. 验证栈序列

946. 验证栈序列

图床:blogimg/刷题记录/leetcode/946/

刷题代码汇总:https://www.cnblogs.com/geaming/p/16428234.html

题目

image-20220831165147380

思路

使用vector模拟栈的过程

解法

class Solution {
public:
    bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
        vector<int> tmp;
        int pos = 0;
        for(int i = 0;i<pushed.size();i++){
            tmp.push_back(pushed[i]);
            while(!tmp.empty()&&tmp[tmp.size()-1]==popped[pos]){
                tmp.pop_back();
                pos++;
            }
        }
        return tmp.empty();
    }
};
  • 时间复杂度:\(O(n)\)
  • 空间复杂度:\(O(n)\)

直接使用栈:

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

补充

posted @ 2022-08-31 16:57  Geaming  阅读(17)  评论(0编辑  收藏  举报