剑指offer — 栈的弹出序列

来源:互联网 发布:手机炒股什么软件 编辑:程序博客网 时间:2024/05/15 10:28

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

java

import java.util.*;public class Solution {    public boolean IsPopOrder(int [] pushA,int [] popA) {if (pushA == null || popA == null || pushA.length == 0 || popA.length == 0 ||            pushA.length != popA.length) {            return false;        }        int pushIndex = 0;        int popIndex = 0;        Stack<Integer> stack = new Stack<>();        while (popIndex < popA.length) {            while (pushIndex < pushA.length && (stack.isEmpty() || stack.peek() != popA[popIndex])) {                stack.push(pushA[pushIndex++]);            }            if (stack.peek() == popA[popIndex]) {                stack.pop();                popIndex++;            } else {                return false;            }        }        return true;    }}