辅助栈:
辅助栈模拟入栈,出栈情况,i指针指向popped当前需要弹出的数字,与辅助栈栈顶数字对比,相同则辅助栈弹出,且popped指针后移。
c++
class Solution {
public:
bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
if(pushed.size()!=popped.size()){
return false;
}
stack<int> stk;
int i = 0;
for(auto n:pushed){
stk.push(n);
while(!stk.empty() && stk.top() == popped[i]){
stk.pop();
i++;
}
}
return stk.empty();
}
};
python
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
if len(popped) != len(pushed):
return False
stk = []
i = 0
for n in pushed:
stk.append(n)
while stk and stk[-1] == popped[i]:
stk.pop()
i+=1
return not stk
|