20200327——剑指offer 面试题31:栈的压入 弹出序列

解决这个问题很直观的想法是建立一个辅助栈,把输入的第一个序列中数字一次压入该辅助栈,并按照第二个序列的顺序一次从该栈中弹出数字。

总结上述入栈、出栈的过程。我们可以判断一个序列是不是栈的弹出序列的规律,如果下一个弹出的数字刚好是栈顶数字,那么直接弹出,如果下一个弹出的数字不在栈顶,则把亚展薛烈中还没有入栈的数字压入辅助栈,直到把下一个需要弹出的数字压入栈顶为止。如果所有数字都压入栈后仍然没有找到下一个弹出的数字,那么该序列不可能是一个弹出序列。

package question31_stack_list;

import java.util.Stack;

/**
 * @Classname Solution
 * @Description TODO
 * @Date 2020/3/27 13:51
 * @Created by mmz
 */
public class Solution {
    public static boolean isPop(int[] pusha,int[] pushb){
        if(pusha == null || pushb ==null){
            return false;
        }

        Stack<Integer> stack = new Stack<>();

        int j = 0;
        for(int i =0;i<pusha.length;i++){
            stack.push(pusha[i]);
            while(!stack.isEmpty() &&stack.peek() == pushb[j]){
                stack.pop();
                j++;
            }
        }
        return stack.isEmpty();
    }
}


二刷

package question31_栈的压入弹出序列;

import java.util.Stack;

/**
 * @Classname Main
 * @Description TODO
 * @Date 2020/4/11 23:16
 * @Created by mmz
 */
public class Main {
    static Stack<Integer> stack = new Stack<>();

    static boolean Core(int[] arr1,int[] arr2){
        int j = 0;
        for(int i = 0;i<arr1.length;++i){
            stack.push(arr1[i]);
            while(!stack.isEmpty() && stack.peek() == arr2[j]){
                stack.pop();
                j++;
            }
        }
        return stack.isEmpty();
    }

    public static void main(String[] args) {
        int[] arr1 = new int[]{1,2,3,4,5};
        int[] arr2 =new int[]{4,3,5,1,2};
        System.out.println(Core(arr1, arr2));
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值