Sword refers to the twenty-first offer
Let's take a look at the topic together
Idea and code
Some parts of this problem are more difficult to deal with, that is, the popping does not necessarily start popping after it has been pushed.
For example: 1 2 3 4 5 into the stack 4 5 3 2 1 out of the stack
We push into the stack first. When it encounters the same element as the pop, it starts popping,
1 popping
2 popping
3 popping
4 popping and popping 4 are the same, 4 popping, 3 and 5 are different to end poping
5 popping and popping Stack 5 is the same, 5 pops, 3 is the same as pop 3
3 pops
2 pops
1 pops
In this way, the stack is empty. If it is empty, it means it is right. Return true.
Similarly, for
1 2 3 4 5 push, 4 3 5 1 2 pop
1 push
2 push
3 push
4 push 4 is the same as pop 4, 4
pop 3 is the same as pop 3, 3 pops
2 is different from pop 5, end
pop 5 is the same as pop 5, and 5 pop
2 is different from pop 1. End
popping, stacking is all over, the stack can be left 1 and 2 are not empty,
so return false
class Solution {
public:
bool IsPopOrder(vector<int> pushV,vector<int> popV) {
stack<int> temp;
int i=0,j=0,len=pushV.size();
for(;i<len;i++){
temp.push(pushV[i]);
for(;!temp.empty()&&temp.top()==popV[j];j++){
temp.pop();
}
}
return temp.empty();
}
};