946. Validate Stack Sequences

题目:

Given two integer arrays pushed and popped each with distinct values, return true if this could have been the result of a sequence of push and pop operations on an initially empty stack, or false otherwise.

Example 1:

Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4),
pop() -> 4,
push(5),
pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1

Example 2:

Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.

Constraints:

  • 1 <= pushed.length <= 1000
  • 0 <= pushed[i] <= 1000
  • All the elements of pushed are unique.
  • popped.length == pushed.length
  • popped is a permutation of pushed.

思路:

模拟题,直接用一个栈来模拟即可。按顺序往栈内加入pushed里的元素,每一次加入后check栈是否为空和栈顶元素是不是当前popped的元素,如果是的话可以删除,即模拟出栈。正确的出栈顺序下应该正好遍历了一次popped,否则就是错误的。以例子2来看,栈内为[1,2,3,4]时,出栈,4被消掉,此时cur为1,即指向3;之后加入5,栈内为[1,2,3,5],同时cur指向的是3,不会被删除,循环结束,cur并没有遍历完整个popped,因此返回false。

代码:

class Solution {
public:
    bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
        int cur = 0;
        stack<int> st;
        for (auto i : pushed) {
            st.push(i);
            while (st.size() && st.top() == popped[cur]) {
                st.pop();
                cur++;
            }
        }
        return cur == popped.size();
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值