Skip to content

Latest commit

 

History

History
33 lines (26 loc) · 826 Bytes

面试题 31:栈的压入、弹出序列.md

File metadata and controls

33 lines (26 loc) · 826 Bytes

试题链接:42. 栈的压入、弹出序列 - AcWing题库

方法一:模拟

  • 思路:模拟栈的压入,压入一个元素后检查栈顶元素是否和出栈序列对应元素匹配。
  • 时间复杂度:O(n)
  • 空间复杂度:O(n)
class Solution {
public:
    bool isPopOrder(vector<int> pushV,vector<int> popV) {
        if (pushV.size() != popV.size()) {
            return false;    
        }
        
        int n = pushV.size();
        stack<int> stk;
        
        int j = 0;
        for (int v : pushV) {
            stk.push(v);
            
            while (j < n && !stk.empty() && stk.top() == popV[j]) {
                stk.pop();
                j++;
            }
        }
        
        return j == n;
    }
};