MENU

剑指Offer 21 栈的压入、弹出序列(栈 / 模拟)

2019 年 05 月 21 日 • 阅读: 906 • 练习阅读设置

剑指Offer21. 栈的压入、弹出序列(栈 / 模拟)

  • 时间限制:1秒
  • 空间限制:32768K
  • 热度指数:330348
  • 本题知识点:

题目描述

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)

链接

https://www.nowcoder.com/practice/d77d11405cc7470d82554cb392585106?tpId=13&tqId=11174&tPage=2&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

题解

使用一个辅助栈来模拟入栈与出栈的操作,如果当前辅助栈栈顶元素与弹出栈元素(也从栈顶开始)相等,那么辅助栈栈顶元素出栈,直至最后判断辅助栈是否为空,如果为空符合题目要求。

  • 时间复杂度:$O(n)$

代码

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

The end.
2019年5月21日 星期二
最后编辑于: 2020 年 04 月 24 日