美文网首页
【剑指31】栈的压入、弹出序列

【剑指31】栈的压入、弹出序列

作者: 浅浅星空 | 来源:发表于2019-07-31 23:36 被阅读0次

题目描述

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

分析(个人思路,有更简单的写法)

    public boolean IsPopOrder(int[] pushA, int[] popA) {
        if (pushA == null || pushA.length == 0) return false;
        if (popA == null || popA.length == 0) return false;
        int pushLength = pushA.length;
        int popLength = popA.length;
        if (popLength > pushLength) return false;
        Stack<Integer> stack = new Stack<>();

        int pushIndex = 0, popIndex = 0;
        while (popIndex < popLength) {
            if (pushIndex == pushLength) {
                if (!stack.empty()) {
                    if (stack.peek() == popA[popIndex]) {
                        stack.pop();
                        popIndex++;
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }
            } else {
                if (!stack.empty()) {
                    if (stack.peek() == popA[popIndex]) {
                        stack.pop();
                        popIndex++;
                        continue;
                    }
                }
                if (pushA[pushIndex] == popA[popIndex]) {
                    popIndex++;
                    pushIndex++;
                } else {
                    stack.push(pushA[pushIndex]);
                    pushIndex++;
                }
            }
        }
        return true;
    }

2.另一种简便思路

    public boolean IsPopOrder(int[] pushA, int[] popA) {
        if (pushA == null && popA == null) return true;
        if (pushA == null || popA == null) return false;
        if (pushA.length != popA.length) return false;

        int i = 0;
        int j = 0;
        Stack<Integer> stack = new Stack<>();
        while (i < pushA.length) {
            stack.push(pushA[i]);
            i++;
            while (j < popA.length && !stack.empty() && stack.peek() == popA[j]) {
                stack.pop();
                j++;
            }
        }
        return stack.empty();
    }

相关文章

网友评论

      本文标题:【剑指31】栈的压入、弹出序列

      本文链接:https://www.haomeiwen.com/subject/oqqfdctx.html