/*
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
*/
class Solution {
public:
// Main Idea:
// Input vector: 1,2,3,4,5 we try to test 4,5,3,2,1
// assist statck: we try to push input vector sequentially
// 1,2,3,4 match 4 pop it 1,2,3 left
// we continue push input 5 then 1,2,3,5 match 5 pop it 1,2,3 left
// similarly try others
// all matched return true
bool IsPopOrder(vector<int> pushV,vector<int> popV) {
if(pushV.size() != popV.size() || pushV.size() == 0) return false ;
std::stack<int> st ;// assist stack
st.push(pushV[0]) ;
int nPushIndex = 1 ;
for(std::size_t i = 0; i < popV.size(); ++i) {
while(!st.empty() && popV[i] != st.top() && nPushIndex < pushV.size()) {// if not match top, only way is try to push more
st.push(pushV[nPushIndex++]) ;// nPushIndex++
}
if(st.empty() || popV[i] != st.top()) {// if still not match top, then return false
// if(popV[i] != st.top()) is also okay
return false ;
}else {
st.pop() ;// if matched pop it
}
}
return true ;
}
};
栈的压入、弹出序列
最新推荐文章于 2022-11-05 17:48:46 发布