Topic source: Niuke.com
programming connection
Topic description
Input two integer sequences. The first sequence represents the stack's push sequence. Please check whether the second sequence is the stack's pop-up sequence. Assume that all numbers pushed onto the stack are not equal. For example, the sequence 1, 2, 3, 4, 5 is the push sequence of a stack, the sequence 4, 5, 3, 2, 1 is a pop sequence corresponding to the stack sequence, but 4, 3, 5, 1, 2 It cannot be the pop sequence of the push sequence. (Note: the two sequences are of equal length)
Parse:
- Use a stack to save the push data and analyze the entire push and pop process.
- Keep pushing and pushing the stack, and when the number pushed and the number popped are found to be the same, pop the number
- If the last data in the stack is 0, it means that the push and pop data are matched.
step | operate | stack | Pop up numbers | Remark |
---|---|---|---|---|
1 | push in 1 | 1 | ||
2 | Press in 2 | 1,2 | ||
3 | Press in 3 | 1,2,3 | ||
4 | Press in 4 | 1,2,3,4 | ||
5 | pop up | 1,2,3 | 4 | Because it is the same as the popup number |
6 | Press in 5 | 1,2,3,5 | ||
7 | pop up | 1,2,3 | 5 | Because it is the same as the popup number |
8 | pop up | 1,2 | 3 | Because it is the same as the popup number |
9 | pop up | 1 | 2 | Because it is the same as the popup number |
8 | pop up | 1 | Because it is the same as the popup number |
….
Code:
class Solution {
public:
bool IsPopOrder(vector<int> pushV,vector<int> popV) {
stack<int> st;
for(int i=0,j=0;i<pushV.size();i++)
{
for(st.push(pushV[i]);j<popV.size()&&st.top()==popV[j]&&!st.empty();st.pop(),j++);//只有在相等的时候才弹出
}
return st.empty();
}
};