zoukankan      html  css  js  c++  java
  • 剑指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;
        }
    }
  • 相关阅读:
    Making Pimpl Easy
    OpenCV学习资源
    openCV基础学习(1)
    fl2440原始linux代码的启动日志
    《s3c2440+lan91c111 vxworks驱动调试》疑惑
    使用并行的方法计算斐波那契数列 (Fibonacci)
    [译] SolidWorks的发展历史(1994~2007)
    翻译介绍一点CAD发展的历史
    使用fopen的两点注意事项
    四元数(Quaternions)简介
  • 原文地址:https://www.cnblogs.com/ttzz/p/13823226.html
Copyright © 2011-2022 走看看