思路
K神的,模拟栈
作者:jyd
链接:https://leetcode-cn.com/problems/zhan-de-ya-ru-dan-chu-xu-lie-lcof/solution/mian-shi-ti-31-zhan-de-ya-ru-dan-chu-xu-lie-mo-n-2/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
class Solution {
public:
bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
// 用一个栈来模拟
stack<int> s;
int i = 0, j = 0; // i是pushed的索引, j是poped的索引
for(i=0; i<pushed.size(); i++){
// 模拟入栈
s.push(pushed[i]);
// 模拟出栈
while(!s.empty() && s.top()==popped[j]){ // s不为空才能取top
s.pop();
j++;
}
}
return s.empty();
}
};