《剑指offer》面试题22 栈的压入、弹出序列 Java版

(输入两个整数序列,第一个序列是一串数字的压入顺序,判断第二个序列是否是该栈数字的弹出顺序。)

我的方法:压入序列是给定的,每一次弹出操作形成一个弹出序列的值,我们从前往后遍历弹出序列,每一次访问弹出序列都代表了一次弹出操作,弹出的值必然是当前栈顶的元素或者是在剩余没有压入的元素序列中。我们要做的是去检查当前弹出的这个元素是否合理,即是否在栈顶或者剩下未压入栈的元素中

这里写图片描述

        public boolean check(int[] inSerial, int[] outSerial){
            int N = inSerial.length;
            //存储已经压入未被弹出的值
            Stack<Integer> left = new Stack<Integer>();
            int toPush = 0;
            int toPop = 0;
            //如果还有未被弹出的值或者还有没有被压入的元素,则继续检查弹出序列
            while(!left.isEmpty() || toPush < N){
                //如果当前弹出元素 并不在栈中,也不是下一个压入元素,则继续检查后一个压入元素。
                if(toPush < N && toPop < N && inSerial[toPush] != outSerial[toPop] 
                        && (left.isEmpty() || left.peek() != outSerial[toPop])){
                    left.push(inSerial[toPush]);
                    toPush++;
                }
                //如果当前弹出元素在栈顶,弹出这个元素,并继续检查下一个弹出元素。
                else if(!left.isEmpty() && left.peek() == outSerial[toPop]){
                    left.pop();
                    toPop++;
                }
                //如果当前弹出元素是下一个压入元素,则继续检查下一个弹出元素,同时也将压入元素指针后移。
                else if(toPush < N && inSerial[toPush] == outSerial[toPop]){
                    toPush++;
                    toPop++;
                }
                //如果出现 当前弹出元素既不在栈顶,也不在压入元素序列内,则表示这个弹出序列是错误的。
                if (toPush == N && !left.isEmpty() && left.peek() != outSerial[toPop]) {
                    return false;
                }
            }
            return true;
        }
        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            CheckInAndOutSerialForStack c = new CheckInAndOutSerialForStack();
            int[] a = new int[]{1,2,3,4,5};
            int[] b = new int[]{4,3,2,1,5};
            System.out.print(c.check(a, b));
        }

猜你喜欢

转载自www.cnblogs.com/czjk/p/11640097.html