剑指offer 栈的压入、弹出序列

题目:

  输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)

代码:

 1 class Solution {
 2 public:
 3     bool IsPopOrder(vector<int> pushV,vector<int> popV) {
 4         stack<int> st;
 5         int length = pushV.size(), i = 0, j = 0;
 6         //按照压入顺序,入栈元素
 7         while( i < length ){
 8             if(st.empty())
 9                 st.push( pushV[i ++] );
10             if(st.top() == popV[j]){ //判断是否存在,在入栈过程中有出栈情况
11                 st.pop(); j ++;
12             }
13             else
14                 st.push( pushV[i ++] );
15         }
16         //将栈中元素依次出栈,并与出栈顺序比较,若不相同,则直接返回false 
17         while( !st.empty() ){ 
18             if( st.top() != popV[j] )
19                return false;
20             else{
21                 st.pop();j ++;
22             }
23         }
24         return true;
25     }
26 };

我的笔记:

  由于本题存在可能在入栈过程中先出栈的情况,所以要做特殊处理。

原文地址:https://www.cnblogs.com/john1015/p/12956456.html