leetcode 946. Validate Stack Sequences

本文介绍了一种使用栈数据结构来验证两个整数数组是否符合栈的压入和弹出顺序的方法。通过迭代检查,当栈为空或栈顶元素不等于待弹出元素时,将元素压入栈;当两者相等时,进行弹出操作。该方法能够高效地判断给定序列是否有效。

Just use a stack to simulate the push and pop process

While stack is empty or peek does not equal to popped current value, push value into stack.

While equal, pop stack and consume popped value.

    class Solution {
        public boolean validateStackSequences(int[] pushed, int[] popped) {
            Stack<Integer> s = new Stack<Integer>();
            int i = 0, j = 0;
            while (j < popped.length) {
                if (s.size() == 0 || s.peek() != popped[j]) {
                    if (i == pushed.length) return false;
                    s.push(pushed[i++]);
                }
                else {
                    s.pop();
                    ++j;
                }
            }
            return true;
        }
    }

转载于:https://www.cnblogs.com/exhausttolive/p/10561470.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值