剑指offer31:栈的压入弹出序列

题目描述

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
 
自己写的非常复杂的思路
class Solution {
public:
    bool IsPopOrder(vector<int> pushV,vector<int> popV) {
        int len = pushV.size();
        if(len == 0) return true;
        int * flag = new int[pushV.size()];
        memset(flag,0,len*sizeof(int));
        stack<int> s;
        vector<int>::iterator itIndex;
        for(vector<int>::iterator it = popV.begin();it!=popV.end();it++){
            itIndex = find(pushV.begin(),pushV.end(),*it);
            int index = &*itIndex-&pushV[0];
            for(int i = 0;i<=index;i++){
                    if(flag[i]==0){
                        s.push(pushV[i]);
                        flag[i] = 1;
                    }
                }
                if(s.empty())
                    return false;
                else{
                    if(s.top()!=*it){
                        return false;
                    }else{
                        flag[index]=-1;
                        s.pop();
                    }
                }
        }
        return true;
    }
};

看了评论区后的算法:

class Solution {
    public boolean validateStackSequences(int[] pushed, int[] popped) {
        if(pushed.length == 0) return true;
        Stack<Integer> s = new Stack<>();
        int j=0;
        for(int i=0;i<pushed.length;i++){
            s.push(pushed[i]);
            while(!s.empty()&&s.peek().equals(popped[j])){
                s.pop();
                j++;
            }
        }
        if(!s.empty())
            return false;
        return true;
    }
}
原文地址:https://www.cnblogs.com/ttzz/p/13823226.html