Stack

难点:入栈出栈条件的判断。

给出栈的压入序列12345,判断弹出序列45231是否正确(false): 使用辅助栈stack压入pushA序列,stack栈顶元素和popA[popIndex]进行比较。最后检查stack是否为空。

public class Solution {
    public boolean IsPopOrder(int [] pushA,int [] popA) {
        if (pushA.length == 0 || popA.length == 0) return false;
        LinkedList<Integer> stack = new LinkedList<>();
        int popIndex = 0;
        for (int i = 0; i < popA.length; i++) {
            stack.push(pushA[i]);
            while (!stack.isEmpty() && popA[popIndex] == stack.peek()) {
                stack.pop();
                popIndex++;
            }
        }
        return stack.isEmpty();
    }
}

如果有n个数字出入栈,那么出栈序列:

https://zh.wikipedia.org/wiki/%E5%8D%A1%E5%A1%94%E5%85%B0%E6%95%B0

results matching ""

    No results matching ""