Acwing_42 栈的压入、弹出序列

Acwing_42 栈的压入、弹出序列

解题思路:
1、如果当前压入辅助栈helpStack的栈顶元素的值与弹出序列的index下标所指的元素的值相同,那么将辅助栈的栈顶元素弹出,并且index++,向后移动一位
2、如果当前压入辅助栈helpStack的栈顶元素的值与弹出序列的index下标所指的元素的值不相同,那么继续将压入序列中的元素压入辅助栈中,直到相同为止
3、如果最终辅助栈中为空,没有任何元素则返回true

public class A_42 {
    private static Stack<Integer> helpStack = new Stack<Integer>(); //辅助栈

    public static void main(String[] args) {
        A_42 a_42 = new A_42();
        int[] pushArr = {1,2,3,4,5};
        int[] popArr = {4,5,3,2,1};
        int[] push = {8,2,7,4,5};
        int[] pop = {7,5,2,8,4};
        System.out.println(a_42.isPopOrder(pushArr, popArr));
        System.out.println(a_42.isPopOrder(push, pop));
    }

    public boolean isPopOrder(int [] pushV,int [] popV) {
        //若两个序列长度不等则视为并不是一个栈的压入、弹出序列
        if (pushV.length != popV.length){
            return false;
        }
        //若两个序列都为空,则视为是一个栈的压入、弹出序列
        if (pushV.length == 0 && popV.length == 0){
            return true;
        }
        int index = 0;
        for (int i = 0; i < pushV.length; i++){
            helpStack.push(pushV[i]);
            //辅助栈不为空 且 辅助栈的栈顶元素与弹出序列的中index下标所对应的值相同
            while (!helpStack.isEmpty() && helpStack.peek() == popV[index]){
                helpStack.pop();
                index ++;
            }
        }
        return helpStack.isEmpty();
    }
}

运行结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值