【栈】验证栈序列

题目描述

给定 pushed 和 popped 两个序列,每个序列中的 值都不重复,只有当它们可能是在最初空栈上进行的推入 push 和弹出 pop 操作序列的结果时,返回 true;否则,返回 false 。

示例 1:

输入:pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
输出:true
解释:我们可以按以下顺序执行:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1

解题思路

这道题直接使用栈来模拟操作,实现思路:

  • 循环遍历pushed数组;
    • 将数据push到栈中;
    • 如果栈顶数据和popped数据相等,则出栈;
  • 遍历栈中剩余元素,如果栈顶数据和popped数据相等,则出栈;否则直接返回false。

整体代码如下:

import java.util.ArrayDeque;
import java.util.Deque;

class Solution1 {

    public boolean validateStackSequences(int[] pushed, int[] popped) {

        int poppedIndex = 0;

        Deque<Integer> deque = new ArrayDeque<>(pushed.length);

        for (int i = 0; i < pushed.length; ) {
            if (deque.isEmpty()) {
                deque.push(pushed[i]);
                i++;
            } else {
                int v = deque.peek();
                if (v == popped[poppedIndex]) {
                    deque.pop();
                    poppedIndex++;
                } else {
                    deque.push(pushed[i]);
                    i++;
                }
            }
        }
        while (!deque.isEmpty()) {
            int v = deque.peek();
            if (v == popped[poppedIndex]) {
                deque.pop();
                poppedIndex++;
            } else {
                return false;
            }
        }
        return deque.isEmpty();
    }

    public static void main(String[] args) {
        //[1,2,3,4,5]
        //[4,5,3,2,1]

        Solution1 solution = new Solution1();
        System.out.println(solution.validateStackSequences(new int[]{1, 2, 3, 4, 5}, new int[]{4, 5, 3, 2, 1}));
    }
}

这道题还能进一步优化,简化代码操作:

遍历操作时,如果栈顶元素和popped数据相等,则进入循环,循环是将栈顶元素出栈;具体代码实现如下:


import java.util.ArrayDeque;
import java.util.Deque;

class Solution {

    public boolean validateStackSequences(int[] pushed, int[] popped) {

        int poppedIndex = 0;

        Deque<Integer> deque = new ArrayDeque<>(pushed.length);

        for (int i = 0; i < pushed.length; i++) {

            deque.push(pushed[i]);

            while (!deque.isEmpty() && deque.peek() == popped[poppedIndex]) {
                deque.pop();
                poppedIndex++;
            }
        }
        return deque.isEmpty();
    }

    public static void main(String[] args) {
        //[1,2,3,4,5]
        //[4,5,3,2,1]

        Solution solution = new Solution();
        System.out.println(solution.validateStackSequences(new int[]{1, 2, 3, 4, 5}, new int[]{4, 5, 3, 2, 1}));
    }
}

 

 

总结

这道题中等难度,利用栈来模拟操作,能解决上述问题;从这个数据上看还有优化空间,如果有更高效、更简洁的代码欢迎回复。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值