剑指offer:栈的压入弹出序列
class Solution{ public: bool IsPopOrder(vector<int> pushV,vector<int> popV ){ if(pushV.size()==0 ||popV.size()==0||pushV.size()!= popV.size()) return false; int len=pushV.size(); int popIndex= 0; stack<int> st; for(int i=0;i<len;++i){ st.push(pushV[i]); while(popIndex<len && !st.empty()&& st.top()==popV[popIndex]) { st.pop(); popIndex++; } } return st.empty(); } };
首先定义两个数组,一个进栈一个弹出;当其中一个数组的大小为0或者两者长度不相等时,返回false;定义弹出数组的第一位为0,在定义一个辅助栈st,for循环,i小于数组长度,就压入数据,但是当popIndex<len && !st.empty()&& st.top()==popV[popIndex](这个是st栈的第一个元素等于弹出数组的元素)这些条件满足时,便弹出对应的元素,然后popIndex++,把栈和弹出数组的值都遍历遍,都对应时就是它的弹出序列;
#剑指offr#