思路:
主要关注popped数组,因为popped是已经固定了的,而push的顺序可以根据popped来推导
按照popped数组来构建push的顺序,保证栈顶为poped即可,对于popped和pushed数组的遍历用到了双指针思想
class Solution {
public:
bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
stack<int> s;
int n = pushed.size(), i = 0, j = 0;
while(i<n && j<=n){
if(s.empty() || s.top() != popped[i]){
if(j >= n){
return false;
}
s.push(pushed[j++]);
} else if(s.top() == popped[i]){
++i;
s.pop();
} else{
return false;
}
}
if(j == n && s.empty()){
return true;
}
return false;
}
};