通过一个栈来模拟,扫描pushed数组,入栈,判断poped数组中的元素是否等于当前入栈的元素,如果相等,一直出栈。
最后判断栈是否为空。空了就说明顺序是对的。
class Solution {
public:
bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
stack<int>s;
int j=0;
for(int i=0;i<pushed.size();i++){
s.push(pushed[i]);
while(!s.empty()&&s.top()==popped[j]){
s.pop();
j++;
}
}
return s.empty();
}
};