• 剑指Offer_21_栈的压入、弹出序列


    题目描述

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

    解题思路

    遍历两个数组,首先判断入栈元素是否和出栈队列当前元素相同,如果相同,则两个数组都指向下一个元素,如果不相等,则将第一个数组的元素入栈。每次第二个数组中的元素需要和栈顶元素以及第一个数组元素比较。如果最后遍历完成两个数组且栈为空,则说明是出栈顺序。

    实现

    import java.util.LinkedList;
    
    public class Solution {
        public boolean IsPopOrder(int [] pushA,int [] popA) {
            if (popA == null && pushA == null) return true;
            else if (popA == null || pushA == null) return false;
            else if (popA.length != pushA.length) return false;
            LinkedList<Integer> stack = new LinkedList<>();
            int pIndex = 0, popIndex = 0;
            while (pIndex < pushA.length){
                if (!stack.isEmpty()){
                    int in = stack.peek();
                    if (popA[popIndex] == in){
                        stack.pop();
                        popIndex++;
                        continue;
                    }
                }
                stack.push(pushA[pIndex++]);
            }
            while (!stack.isEmpty() && popA[popIndex] == stack.peek()){
                stack.pop();
                popIndex ++;
            }
            if (!stack.isEmpty() || popIndex != popA.length) return false;
            return true;
        }
    }
    
  • 相关阅读:
    6 15种对抗攻击的防御方法
    5 12种生成对抗样本的方法
    4 基于优化的攻击——CW
    3 基于梯度的攻击——MIM
    Hibernate 5 Maven 仓库的 Artifacts
    Hibernate 5 发行组件下载
    Hibernate 5 的模块/包(modules/artifacts)
    Hibernate 5 开始使用指南前言
    Git 如何针对项目修改本地提交提交人的信息
    Spring Batch 4.2 新特性
  • 原文地址:https://www.cnblogs.com/ggmfengyangdi/p/5775246.html
Copyright © 2020-2023  润新知