- 思路:模拟栈的压入,压入一个元素后检查栈顶元素是否和出栈序列对应元素匹配。
- 时间复杂度: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;
}
};