题目地址:
https://www.acwing.com/problem/content/description/40/
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列 1 , 2 , 3 , 4 , 5 1,2,3,4,5 1,2,3,4,5是某栈的压入顺序,序列 4 , 5 , 3 , 2 , 1 4,5,3,2,1 4,5,3,2,1是该压栈序列对应的一个弹出序列,但 4 , 3 , 5 , 1 , 2 4,3,5,1,2 4,3,5,1,2就不可能是该压栈序列的弹出序列。注意:若两个序列长度不等则视为并不是一个栈的压入、弹出序列。若两个序列都为空,则视为是一个栈的压入、弹出序列。
数据范围:
序列长度
[
0
,
1000
]
[0,1000]
[0,1000]。
直接模拟即可。代码如下:
#include <vector>
#include <stack>
using namespace std;
class Solution {
public:
bool isPopOrder(vector<int> pushV,vector<int> popV) {
if (pushV.size() != popV.size()) return false;
stack<int> stk;
int idx = 0;
for (auto x : pushV) {
stk.push(x);
while (stk.size() && stk.top() == popV[idx]) {
stk.pop();
idx++;
}
}
return stk.empty();
}
};
时空复杂度 O ( n ) O(n) O(n), n n n为序列长度。