原题目:https://leetcode-cn.com/problems/validate-stack-sequences/
思路:
使用栈模拟进出过程,如果栈顶元素和popped[index]相等,就进行出栈操作,直到不满足条件。否则对pushed数组进栈。
最后如果栈为空并且index到达了popped数组的尾部,就代表成功。
代码:
class Solution {
public:
bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
stack<int> s;
int index = 0;
for(int &num:pushed){
s.push(num);
while(!s.empty() && s.top()==popped[index]){
s.pop();++index;
}
}
return s.empty() && index == popped.size();
}
};