剑指 31

该博客主要介绍了如何验证一个给定的压入弹出序列是否可能来自某个栈。提供了两种简洁的Java实现思路,通过不断模拟栈的压入和弹出操作来检查序列是否匹配。第一种思路是在每次压入后尝试弹出,直到弹出序列匹配;第二种思路则是使用一个指针记录下次压入的位置,并在每次遍历结束后检查栈是否为空。两种方法都以栈操作和序列匹配为核心,简化了代码逻辑。
摘要由CSDN通过智能技术生成

剑指 Offer 31. 栈的压入、弹出序列

题目:

在这里插入图片描述

思路:

看了剑指的思路做的,虽然代码不一样,但是代码都显得乱。简单说下思路:
思路一:
1.按照push的顺序往stack中push,知道poped[0]
2.然后进行stack.pop,如果poped[0++]和stack.peek() 不相等了。那么在pushed里接着找peek,没找到就退出,找到就向1一样,继续往stack中放置
3.注意:思路就是这个思路,自己写的时候一直没有对pushed的位置进行判断导致一直提交报错,睡了一觉,多加了一个参数,if校验也变少了,直接过了
(语言行描述确实有点乱,show code or picture)
思路二:
其实上面的思路容易理解,但是代码的实现还是较为复杂,没有什么章法。if退出条件也试了多次,翻了翻其他人的题解,还是这种思路只不过简化了下——按照push的顺序,每次放完后,判断是否和pushed相等,相等就一直pop。当push放完后,直接判断是否pop完成即可。

题解:

class Solution {
    public boolean validateStackSequences(int[] pushed, int[] popped) {
        Stack<Integer> stack = new Stack<>();
        int popedInt = 0;
        for (int i = 0; i < pushed.length; i++) {
            stack.push(pushed[i]);
            // 每次push后就进行判断是否要pop
            while (!stack.isEmpty() && stack.peek() == popped[popedInt]) {
                stack.pop();
                popedInt++;
            }
        }
        // 直接返回结果
        return popedInt == popped.length;
    }
}
class Solution {
    public boolean validateStackSequences(int[] pushed, int[] popped) {
    	// 空,或者一个为空的判断
        if (pushed.length == 0 && popped.length == 0) {
            return true;
        }
        if (pushed.length == 0 || popped.length == 0) {
            return false;
        }
        // 下次pushed开始的地方
        int temp = -1;
        // pushed的计数,到头了并且stack还没pop完就退出
        int pushInt = 0;
        Stack<Integer> stack = new Stack<>();
        // poped的技术
        int count = 0;
        while (true) {
            for (int i = temp+1; i < pushed.length; i++) {
                stack.push(pushed[i]);
                pushInt = i;
                if (pushed[i] == popped[count]) {
                    temp = i;
                    break;
                }
            }
            while ( !stack.isEmpty() && stack.peek() == popped[count]) {
                stack.pop();
                count++;
            }
            // pop数组验证完了,就退出
            if (count > popped.length - 1 && stack.isEmpty()) {
                return true;
            }
            // 引入一个pushed数组的计数,如果用完了,但是stack还没pop完就退出
            if (pushInt >= pushed.length - 1) {
                if (stack.isEmpty()) {
                    return true;
                }
                return false;
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值