一刷剑指Offer_31:栈的压入和弹出序列

1、题目描述:
在这里插入图片描述
2、思路:

尝试按照 popped 中的顺序模拟一下出栈操作,如果符合则返回 true,否则返回 false。这里用到的贪心法则是如果栈顶元素等于 popped 序列中下一个要 pop 的值,则应立刻将该值 pop 出来。

使用一个栈来模拟该操作。将 pushed 数组中的每个数依次入栈,同时判断这个数是不是 popped 数组中下一个要 pop 的值,如果是就把它 pop 出来。最后检查栈是否为空。

在这里插入图片描述
3、实现方式1:

class Solution {
    public boolean validateStackSequences(int[] pushed, int[] popped) {
    
        Stack<Integer> stack = new Stack<Integer>();
        int j = 0;
        for(int i = 0;i <= pushed.length-1;i++){
            stack.push(pushed[i]);
            while(!stack.empty() && j <= popped.length-1 && stack.peek() == popped[j]){
                stack.pop();
                j++;
            }
        }
        return stack.empty();
    }
}

4、实现方式2:

class Solution2 {
    public boolean validateStackSequences(int[] pushed, int[] popped) {
        Stack<Integer> stack = new Stack<>();
        int j = 0;

        /**
         * 1、如果栈中没有任何元素,len=0,调用peek()方法会抛出异常EmptyStackException
         * 2、当栈中还没有任何元素入栈时,判断stack.empty(),就不会判断后面的条件了
         * 3、当栈中有元素入栈后,判断stack.peek() != popped[poppedIndex]
         */
        for (int i = 0; i <= popped.length-1;i++) {
            while (j <= pushed.length-1 && (stack.empty() || stack.peek() != popped[i])){
                stack.push(pushed[j]);
                j++;
            }
            if(stack.peek()!=popped[i]){
                return false;
            }else{
                stack.pop();
            }
        }
        return true;
    }
}

5、测试类:

public class Main {
    public static void main(String[] args) {
        int[] pushed = {1,2,3,4,5};
//        int[] poped = {4,5,3,2,1};
        int[] poped = {4,3,5,1,2};

        Solution solution = new Solution();
        System.out.println(solution.validateStackSequences(pushed, poped));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我一直在流浪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值