题目
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1、2、3、4、5是某栈的压栈序列,序列4、5、3、2、1是该压栈序列对应的一个弹出序列,但4、3、5、1、2就不可能是该压栈序列的弹出序列。
思路
- 如果下一个弹出的数字不在栈顶,则可能要弹出的数字还没入栈,接着把压入序列中的数字接着入栈,直到下一个需弹出的数字在栈顶
- 如果下一个弹出的数字是栈顶数字,那么直接弹出
- 如果把压入序列中的所有数字都入栈还没找到要弹出的数字,那么该序列不可能是一个弹出序列
class Solution { public: bool IsPopOrder(vector<int> push,vector<int> pop) { if(push.size()!=pop.size()) return false; stack<int> s; for(int i=0,j=0;i<push.size();++i) { s.push(push[i]); while(j<push.size()&&pop[j]==s.top()) { ++j; s.pop(); } } return s.empty(); } };