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

本文介绍了一个算法问题,即如何判断给定的两个整数序列,第一个序列表示栈的压入顺序,第二个序列是否为该栈的有效弹出顺序。通过使用辅助栈并结合两个指针的方法,实现了这一功能的高效判断。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。

   例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)

思路:两个数组,一个是push序列,一个是pop序列,需要两个指针,一个是pushIndex, 另一个是popIndex, 还需要一个辅助栈。当pushIndex < len(数组的长度)且 (stack为空或stack的栈顶不等于pop序列时),将push序列中的元素压入到stack中。

public class StackPushAndPop {
    
    public static void main(String[] args){
        /*Scanner s = new Scanner(System.in);
        while(s.hasNext()){
            int len = s.nextInt();
            int[] push = new int[len];
            for(int i =0 ; i < len;i++){
                push[i] = s.nextInt();
            }
            int[] pop = new int[len];
            for(int i = 0; i < len;i++){
                pop[i] = s.nextInt();
            }
            boolean result = IsPopOrder(push,pop);
            System.out.println(result);
        }*/
        int push[] = new int[]{1,2,3,4,5};
        int pop[] = new int[]{5,3,4,2,1};
        boolean result = IsPopOrder(push,pop);
        System.out.println(result);
        
    }
    public static boolean IsPopOrder(int[] pushA, int[] popA) {
        Stack<Integer> stack = new Stack<Integer>();
        if(pushA == null || popA == null || popA.length == 0 || pushA.length == 0 || pushA.length != popA.length){
            return false;
        }
        int pushIndex = 0;
        int popIndex = 0;
        while(popIndex < popA.length){
            while( (pushIndex < pushA.length) && (stack.isEmpty() || popA[popIndex] != stack.peek()))     {
                stack.push(pushA[pushIndex]);
                pushIndex++;
            }
            if(stack.peek() == popA[popIndex]){
                stack.pop();
                popIndex++;
            }else{
                return false;
            }
        }
        return true;
    }

}

 

转载于:https://www.cnblogs.com/lfdingye/p/7299335.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值